[문법] Codable

2023. 8. 18. 16:17Swift

320x100
Codable

외부 표현으로 변환하거나 외부 표현으로 변환할 수 있는 유형입니다.

출처 : https://developer.apple.com/documentation/swift/codable

 

typealias Codable = Decodable & Encodable

Codable은 Decodable과 Encodable이 합쳐진 타입이다. Decodable은 어떤 데이터를 Decoding할 수 있는 타입이고, Encodable은 어떤 객체를 Encoding할 수 있는 타입이다.

Decodable

let jsonFromServer = """
{
    "nick_name" : "개발하는 정대리",
    "job" : "유튜버, 개발자",
    "user_name" : "dev_jeongdaeri"
}
"""

이런 JSON 데이터가 있다고 할 때, 이를 클래스 또는 스트럭트로 디코딩해주는 타입이다.

struct User : Decodable {
    var nickname : String
    var job : String
    var myUsername : String
}

클래스 또는 스트럭트 이름 뒤에 Decodable을 넣게 되면, JSONDecoder()를 통해 데이터를 저장할 수 있다.

...
guard let jsonData : Data = jsonString.data(using: .utf8) else{
    return nil
}
do{
    let user = try JSONDecoder().decode(User.self, from: jsonData)
    print("user: \(user)")
    return user
} catch {
    print("에러발생")
    return nil
}
...

이때 데이터를 Data 타입으로 변환하고, Decoding해야된다.

또한 에러가 발생할 수 있기 때문에, docatch를 사용해 에러처리를 해야 한다

 

출처 : 개발하는 정대리 스위프트 기초 문법 인프런 강의
728x90

'Swift' 카테고리의 다른 글

NotificationCenter  (2) 2023.10.24
[문법] 프로토콜  (0) 2023.08.15
[문법] Error  (0) 2023.08.14
[문법] inout  (0) 2023.08.14
[문법] Closure  (0) 2023.08.04