공식문서 정의

개요

A type that can convert itself into and out of an external representation.

→ 외부 표현으로 전환할 수 있는 유형

정의

typealias Codable = Decodable & Encodable

내용

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.

→ Codable은 Encodable 및 Decodable 프로토콜의 typealias입니다. Codable을 사용하면 두 프로토콜을 모두 준수해야 한다.

  • Encodable -> data를 Encoder에서 변환해주려는 프로토콜로 바꿔주는 것 ( 모델 → Json )
  • Decodable -> data를 원하는 모델로 Decode 해주는 것 ( Json → 모델 )

⇒ Swift4 버전부터 추가되었으며 기존 Decodable 과 Encodable 을 하나로 합친 프로토콜

⇒ Type 이 모두 지정되어 있는경우 Decoable과 Encodable을 별도 채택 안해도 Codable만으로 사용

⇒ Class , Struct, Enum 상관 없이 모두 사용 가능한 프로토콜!!!

 

코드로 확인

Codable 채택

  • Codable 을 채택한 Struct 생성
struct User: Codable {
    let age: Int
    let name: String
    let phone: String
    let address: String
    
    // Json 정보와 struct의 정보를 파싱하기 위해 사용 CodingKey
    // 이름이 같으면 원형 그대로 사용하고, 다른경우 별도 지정해주면 된다
    enum CodingKeys: String, CodingKey {
        case age
        case name
        case phone = "phone_number"
        case address
    }
}
  • Codable 프로토콜을 User 구조체에 채택
  • 서버로부터 받아오는 데이터의 이름과 구조체에서 정의한 이름이 다를 수 있기 때문에 CodingKey를 이용하여 적용해준다 , 이때 서버와 구조체의 이름이 동일하다면 그대로 사용하면 되며 다를경우 파싱해준다

⇒ 예제 코드에서 Json 데이터의 phone 이름이 phone_number 로 오기 때문에 파싱을 해주었다.

Decodable ( 외부 데이터 → 모델 ) 적용

// Decode
extension User {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        age = try container.decode(Int.self, forKey: .age)
        name = try container.decode(String.self, forKey: .name)
        phone = try container.decode(String.self, forKey: .phone)
        address = try container.decode(String.self, forKey: .address)
    }
}

func decode() {
    let jsonString = """
                            [
                                {
                                    "age": 18,
                                    "name": "홍길동",
                                    "phone_number": "010-1234-5678",
                                    "address": "인천"
                                },
                                {
                                    "age": 19,
                                    "name": "이길동",
                                    "phone_number": "010-1234-5678",
                                    "address": "서울"
                                },
                                {
                                    "age": 23,
                                    "name": "김동길",
                                    "phone_number": "010-1234-5678",
                                    "address": "강원"
                                }
                            ]
                          """
    let jsonData = jsonString.data(using: .utf8)
    do {
        guard let jsonData = jsonData else { return }
        let dataModel = try JSONDecoder().decode([User].self, from: jsonData)
        print(dataModel)
				/*
					 [
							{age 18, name "홍길동", phone "010-1234-5678", address "인천"}, 
							{age 19, name "이길동", phone "010-1234-5678", address "서울"}, 
							{age 23, name "김동길", phone "010-1234-5678", address "강원"}
						]
				*/
    } catch let error {
        print(error)
    }
}

decode()
  • extension 을 이용해 User 모델에 Decode를 적용시킨다
  • Decode의 경우 초기화를 우선 해주어야 하기 때문에 init을 통해 이를 수행한다
  • container 상수에 CodingKey를 적용시킨 Decode 를 수행 각 모델 내의 상수또한 해당 이름으로 파싱한다
  • jsonString 변수에 Json 형태의 데이터가 들어있으므로 이를 우리가 원하는 User 모델로 파싱
  • let dataModel = try JSONDecoder().decode([User].self, from: jsonData) 해당 구문을 통해 Json 형태의 데이터가 User 모델로 파싱된다.

⇒ 해당 구조는 공식문서에도 나와있는 형태이기 때문에 잘 기억하자!

Encode ( 모델 → 외부 데이터 ) 적용

// Encode
extension User {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(age, forKey: .age)
        try container.encode(name, forKey: .name)
        try container.encode(phone, forKey: .phone)
        try container.encode(address, forKey: .address)
    }
}

func encode() {
     let userObject = [
        User(age: 18, name: "홍길동", phone: "010-1234-5678", address: "인천"),
        User(age: 24, name: "김재우", phone: "010-1234-5678", address: "서울"),
        ]
        
     do {
         let jsonData = try JSONEncoder().encode(userObject)
         let jsonString = String(data: jsonData, encoding: .utf8)
         guard let printJsonString = jsonString else { return }
         print(printJsonString)
				/*
					 "[
							{"age":18,"name":"홍길동","phone_number":"010-1234-5678","address":"인천"},
							{"age":24,"name":"김재우","phone_number":"010-1234-5678","address":"서울"}
						]"
				*/
     } catch let error {
         print(error)
     }
}

encode()
  • 이번엔 Json 형태의 데이터를 우리가 만든 User 모델로 파싱하기 위해 Encodable을 사용해 보자
  • Decode와 과정이 비슷하지만 그 순서를 역순으로 하면 된다!
  1. Encoder 를 통해 Json 파일을 인코딩 하고
  2. 인코딩한 데이터를 String 형태로 변환해주고 ( 한글이 포함될 수 있으니 utf8 로! )
  3. 인코딩한 데이터가 nil 인지 파악한후! 사용하면 된다 ( 와! 정말 대단해! )

⇒ Encodable 과 Decodable 을 따로 쓰면 다소 복잡할 수 있지만, Codable 프로토콜을 채택 함 으로써 한번에 적용 시킬수 있다!!!!!

이제 우리가 하려고 하는 API 호출을 통해 원하는 데이터를 받아와 보자 ( 후.. 드디어!! )

+ Recent posts