-
[Swift] Codable 개념 확실히 이해하기 💬Swift 2023. 10. 6. 21:36
Codable: type alias
Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.
Coadable은 Encodable과 Decodable을 합친 Union Type이다.정의
typealias Codable = Decodable & Encodable
Decodable: Protocol
A type that can decode itself from an external representation.
Decodable은 외부 표현을 자신으로 변환(decode)할 수 있는 타입이다.Encodable: Protocol
A type that can encode itself to an external representation.
Encodable은 자신을 외부표현으로 변환(encode)할 수 있는 타입이다.Codable 활용
Codable은 json등 외부 표현으로 데이터를 변환(decode)해서 전송하고 또 전달 받는 데이터를 다시 원하는 타입으로 변환(encode)하는 경우 사용하게 된다. 간단한 예시를 통해 활용에 대한 이해를 높여보자.
Encoder, Decoder의 기본적인 활용
struct User: Codable { let id: Int let name: String let age: Int } func encodeUser() { let user = User(id: 1, name: "moonkey", age: 26) let jsonEncoder = JSONEncoder() do { let data = try jsonEncoder.encode(user) print(data) } catch { print(error) } } func decodeUser() { guard let jsonData = """ { "id": 1, "name": "moonkey", "age": 26 } """.data(using: .utf8) else { return } let decoder = JSONDecoder() do { let data = try decoder.decode(User.self, from: jsonData) print(data) } catch { print(error) } } // Output // User(id: 1, name: "moonkey", age: 26) // 34 bytes
문제 상황
CodingKey: Protocol
CodingKey는 encoding과 decoding을 위한 키로 사용할 수 있는 타입이다. 아래와 같이 Codable 내에 작성한 뒤 바꾸고 싶은 이름을 설정하면 아래와 같이 다른 이름이 들어오더라도 encode할 수 있게 된다.
struct User: Codable { let id: Int let name: String let age: Int enum CodingKeys: String, CodingKey { case id = "user_id" case name = "user_name" case age = "user_age" } } ... { "user_id": 1, "user_name": "moonkey", "user_age": 26 } ...
Reference
Codable | Apple Developer Documentation
'Swift' 카테고리의 다른 글
[Swift] Error Handling 마스터하기(do-catch, throw-try) (1) 2024.01.25 SwiftUI에서 화면 캡쳐하기(with UIKit / UIGraphicsImageRenderer) (0) 2023.10.11 [Swift] defer는 무엇인가 🤔 (0) 2023.10.03 [Swift] \. 는 무엇인가 (KeyPath 정리) (0) 2023.03.23 [SwiftUI] @State와 @ObservableObject 알아보기 (0) 2023.03.21