티스토리 뷰

Mobile/iOS

Swift. Codable Encoding (1)

out of coding 2018. 6. 17. 12:42

Codable을 이용하여 Decode만 하는것이 아니라 Encode도 가능합니다.

왜냐면 Codable은 사실 Encodable & Decodable 을 하여준것입니다.


https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types


그래서 Codable을 딱히 쓰지 않아도 되면 따로 따로 만들어도 됩니다. 후훗


Decode에 관한것은 이전 글에서 참고 바랍니다.


http://mrgamza.tistory.com/562


아래와 같이 한번 만들어 봅시다. 이것을 가지고 Json String을 만들겁니다.


1
2
3
4
5
6
7
8
9
10
struct SampleData: Codable {
    
    var name: String?
    var age: Int
 
    enum CodingKeys: String, CodingKey {
        case name
        case age = "Age"
    }
}
cs


위의 데이터를 가지고 이렇게 encode 하여 줍니다.


1
2
3
4
5
let person = SampleData()
let encoder = JSONEncoder()
if let data = try? encoder.encode(person), let json = String(data: data, encoding: .utf8) {
    print(json)
}
cs


저는 ! <- 옵셔널을 강제로 벗겨내는것을 싫어하느라 코드가 저렇게 되었습니다.


출력을 이쁘게 하고 싶다면 encoder.outputFormatting = .prettyPrinted 를 사용하세요.



'Mobile > iOS' 카테고리의 다른 글

RxSwift. Observable combine  (0) 2018.06.19
RxSwift. Transforming Observable  (0) 2018.06.19
Swift. Codable Decoding (1)  (0) 2018.06.17
RxSwift DisposeBag  (0) 2018.06.13
RxSwift distinct operator  (0) 2018.06.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함