Codable

Allie·2021년 12월 5일
0

❓Codable

: 공식문서를 보면 스스로 뭔가를 변환할 수 있는 느낌인 것 같다.
일단, Codable은? Decodable과 Encodable 프로토콜을 준수하는 타입이라는 것을 알 수 있다.

그럼, Decodable & Encodable은 모냐?

  • Decodable : A type that can decode itself from an external representation
  • Encodable : A type that can encode itself to an external representation
    각각 스스로를 외부표현에서 디코딩 할 수 있는 타입, 스스로를 외부표현으로 인코딩 할 수 있는 타입이라고 한다.

JSON 파싱하기

  • 아래와같은 JSON 파일이 있다고 가정했을 때, decode 해보자!
struct Camper: Codable {
    let name: String
    let point: Int
}

// MARK: - Decode
func decode(from name: String) -> [Camper]? {
        guard let data = NSDataAsset(name: name) else {
            return nil
        }
        
        let camper = try? JSONDecoder().decode([Camper].self, from: data.data)
        
        return camper
    }
  • 추가적으로 decode를 할 때, 아래와 같이 두가지 방법이 있는데 decoder라는 변수가 한 번만 사용되는데 굳이 변수에 담아줄 필요가 없다고 생각되어 바로 사용하는 방법으로 작성했다.
// decoder를 생성해서 변수를 활용하는 방법
let decoder = JSONDecoder()
let camper = try? decoder.decode([Camper].self, from: data.data)

// 바로 사용하는 방법
let camper = try? JSONDecoder().decode([Camper].self, from: data.data)
profile
게발자🦀 되는 중.. 궁김하다.. 궁김해..

0개의 댓글