Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
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
Archives
Today
Total
관리 메뉴

Jupyo's Daily Story

Codable 본문

Swift

Codable

JangJupyo 2024. 9. 30. 12:10
728x90
반응형

CodableEncodableDecodable 프로토콜을 결합한 프로토콜로, 데이터를 다른 형식으로 변환하거나, 다른 형식에서 데이터를 복원할 때 사용됩니다. Codable은 주로 JSON, plist와 같은 포맷에서 사용됩니다.

 

Codable 프로토콜

Codable는 두 가지 프로토콜을 포함합니다.

  • Encodable: 객체를 인코딩(데이터로 변환)
  • Decodable: 데이터를 객체로 디코딩(복원)
struct User: Codable {
    var name: String
    var age: Int
}

 

JSON 인코딩 (객체 -> JSON)

JSONEncoder는 객체를 JSON 형식으로 인코딩합니다.

let user = User(name: "Alice", age: 28)
if let encoded = try? JSONEncoder().encode(user) {
    // JSON 데이터로 변환된 'user'
    print(String(data: encoded, encoding: .utf8))
}

 

JSON 디코딩 (JSON -> 객체)

JSONDecoder는 JSON 데이터를 객체로 디코딩해 줍니다.

let json = """
{
    "name": "Alice",
    "age": 28
}
""".data(using: .utf8)!

if let decoded = try? JSONDecoder().decode(User.self, from: json) {
    print(decoded)
}

 

Codable과 사용자 정의 키

때로는 JSON에서 사용하는 키와 구조체의 변수명이 다를 수 있습니다. 이 경우 CodingKeys라는 열거형을 사용해 매핑할 수 있습니다.

struct User: Codable {
    var username: String
    var birthdate: String
    
    enum CodingKeys: String, CodingKey {
        case username = "user_name"
        case birthdate = "birth_date"
    }
}

이렇게 하면 user_name과 birth_date 키를 username과 birthdate로 매핑할 수 있습니다.

 

Codable의 커스텀 인코딩과 디코딩

기본적인 인코딩/디코딩 외에도, 더 복잡한 로직을 추가하기 위해 커스텀 인코딩 및 디코딩을 구현할 수 있습니다.

struct Event: Codable {
    var name: String
    var date: Date
    
    private enum CodingKeys: String, CodingKey {
        case name
        case date
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        let dateString = try container.decode(String.self, forKey: .date)
        
        // 커스텀 날짜 포맷을 처리
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        guard let parsedDate = formatter.date(from: dateString) else {
            throw DecodingError.dataCorruptedError(forKey: .date, in: container, debugDescription: "Date string does not match format expected by formatter.")
        }
        date = parsedDate
    }
    
    func encode(to encoder: any Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        
        // 날짜를 문자열로 변환
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateString = formatter.string(from: date)
        try container.encode(dateString, forKey: .date)
    }
}

이처럼 커스텀 인코딩과 디코딩을 통해 더욱 복잡한 요구 사항을 처리할 수 있습니다.

 

Codable의 유연성

Codable은 구조체뿐 아니라 클래스, 열거형, 컬렉션에도 적용할 수 있어 범용적으로 사용할 수 있습니다. Swift의 기본 타입인 String, Int, Bool 등도 Codable을 따르기 때문에 복잡한 자료 구조도 쉽게 처리 가능합니다.

 

결론

Codable은 Swift에서 데이터 직렬화역직렬화를 간편하게 할 수 있게 해주는 중요한 도구입니다. 이를 사용해 서버 통신 시 데이터를 JSON으로 변환하거나, 앱 내에서 데이터를 저장하고 불러올 때 쉽게 사용할 수 있습니다. 자동화된 인코딩/디코딩 기능커스텀 매핑을 통해 매우 유연한 데이터 처리 방식을 제공합니다.

반응형

'Swift' 카테고리의 다른 글

ARC (Automatic Reference Counting)  (4) 2024.10.02
클로저 (Closures)  (3) 2024.10.02
OperationQueue  (0) 2024.09.26
Concurrency (async/await)  (3) 2024.09.26
GCD (Grand Central Dispatch)  (1) 2024.09.25