일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 프로젝트
- 자바스크립트
- TypeScript
- 프론트엔드
- 알고리즘
- git
- frontend
- ios
- JavaScript
- iOSDeveloper
- Xcode
- 코딩테스트실력진단
- 코드트리
- react-query
- AppleDeveloperAcademy
- 코딩테스트
- SWIFT
- 프로그래머스
- error
- react
- globalcommunity
- Front-end
- velog
- tshaped
- NextJs
- 코드트리챌린지
- UIKit
- Apple Developer Academy
- 회고
- swiftUI
- Today
- Total
Moon Work
[Swift] Codable 개념 확실히 이해하기 💬 본문
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] 값타입의 Heap Allocation(Heap boxing)은 언제 일어날까? (0) | 2025.03.06 |
---|---|
[Swift] Error Handling 마스터하기(do-catch, throw-try) (1) | 2024.01.25 |
[Swift] defer는 무엇인가 🤔 (0) | 2023.10.03 |
[Swift] \. 는 무엇인가 (KeyPath 정리) (0) | 2023.03.23 |
[Network] URL로 네트워크 요청하기 (0) | 2023.03.12 |