Mobile/iOS
Swift. Codable Encoding (1)
out of coding
2018. 6. 17. 12:42
Codable을 이용하여 Decode만 하는것이 아니라 Encode도 가능합니다.
왜냐면 Codable은 사실 Encodable & Decodable 을 하여준것입니다.
그래서 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 를 사용하세요.