-
[사전캠프 TIL 11일차] Codable (w/ CodingKey)iOS💖 2025. 2. 17. 17:11
학습 키워드
Codable protocol (Encodable, Decodable)
CodingKey protocol
Codable Protocol
: A type alias for Encodable & Decodable- Encodable protocol
- : 인코딩 가능한 데이터를 나타냄
- "A type that can encode itself to an external representation."
➡️ server (외부)에 데이터를 보낼 때, 외부의 표현으로 encoding 해줌 - encode(to: ) 메소드 구현 요구됨
- Decodable protocol
- : 디코딩 가능한 데이터를 나타냄
- "A type that can decode itself from an external representation."
➡️ server 에서 받은 데이터를, 앱 내의 객체형으로 decoding 해줌 - init(from: ) 메소드 구현 요구됨
- Codable protocol
- : Encodable & Decodable 의 type alias
- Codable 사용 = Encodable, Decodable 두 타입 모두 매치된다.
- 기본 자료형 (Int, Double, String 등) 와 Optional 만 지원
- Date, URL, Enum 은 추가 작업해야함
struct Student: Codable { let id: Int let name: String let age: Int }CodingKey Protocol
Codable protocol 의 일부 property의 이름 != JSON 키가 일치하지 않는 경우,
CodingKey protocol 을 사용하여, JSON 키로 매핑시킨다.
struct UserProfile: Codable { let loginID: String let avatarUrl: String let followers: Int let following: Int enum codingKeys: String, CodingKey { case loginId = "login" case avatarUrl = "avatar_url" case followers case following } }출처
https://developer.apple.com/documentation/swift/codable/
Codable | Apple Developer Documentation
A type that can convert itself into and out of an external representation.
developer.apple.com
'iOS💖' 카테고리의 다른 글
[TIL w2d1] Swift 복습 (Tuple, Collection Type, Closure) (0) 2025.03.10 [Project TIL 12일차] 랜덤 컬러 생성 앱 (feat. Clean Code 🎯) (0) 2025.02.20 [사전캠프 TIL 9, 10일차] Combine 딥다이브 🔥 (0) 2025.02.14 [사전캠프 TIL 8일차] Generic (0) 2025.02.13 [사전캠프 TIL 7일차] GCD (DispatchQueue 종류 & 특성) (0) 2025.02.13 - Encodable protocol