Home

Awesome

Sample Swift Codable

Swift Codable Sample 입니다.

Codable

Type Alias

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

Declaration
typealias Codable = Decodable & Encodable

Discussion
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 은 Type Alias 입니다.

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

선언
typealias Codable = Decodable & Encodable

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

통상 사용할 때는 디코딩을 할때 사용하는 것 같습니다.

설명이 잘 되어있는 링크

Sample Source

이해를 돕기위해 셈플 소스를 추가해 봤습니다.

struct SampleStructData01: Codable {
    let id: String
    let code: String
    var order: Int?
    var test: Int?
}

struct SampleStructData02: Codable {
    let code: String
    let data: SampleStructData02SubData
    
    struct SampleStructData02SubData: Codable {
        let id : String
        let code : String
        let order : Int
    }
}

struct SampleStructData03 : Codable {
    let id : String
    var code : String?
    var order : Int
    enum CodingKeys : String, CodingKey{
        case id
        case code
        case order = "order_test"
    }
}

struct SampleStructData04 : Codable {
    let id : String
    let code : String
    let order : Int
}

/// https://github.com/yonaskolb/Codability
struct SampleAnyCodableData01 : Codable {
    let id : AnyCodable
    let code : String
}
struct SampleResponse { }

/**
 {
     userId: 1,
     id: 1,
     title: "delectus aut autem",
     completed: false
 }
 */
extension SampleResponse {
    struct todos: Codable {
        let userId:Int
        let id:Int
        let title: String?
        let completed:Bool?
        
        let testTrash:String?
    }
}

Result Log

===============================
== sampleStructData01()
SampleStructData01(id: "test@gmail.com", code: "abcdefg1234", order: Optional(1), test: nil)
===============================


===============================
== sampleStructData02()
SampleStructData02(code: "poiuytrewq", data: JWSCodableSample.SampleStructData02.SampleStructData02SubData(id: "test@gmail.com", code: "abcdefg1234", order: 1))
===============================


===============================
== sampleStructData03()
SampleStructData03(id: "test@gmail.com", code: Optional("abcdefg1234"), order: 1)
===============================


===============================
== sampleStructData04()
[JWSCodableSample.SampleStructData04(id: "aaaa@gmail.com", code: "1234567890", order: 1), JWSCodableSample.SampleStructData04(id: "bbbb@gmail.com", code: "abcdefghijklmn", order: 2)]
===============================


===============================
== sampleRequest01()
== success
todos(userId: 1, id: 1, title: Optional("delectus aut autem"), completed: Optional(false), testTrash: nil)
== id : 1
===============================