项目作者: ClintJang

项目描述 :
Swift Codable Sample, 간단한 설명과 셈플입니다.
高级语言: Swift
项目地址: git://github.com/ClintJang/sample-swift-codable.git
创建时间: 2018-11-13T08:54:00Z
项目社区:https://github.com/ClintJang/sample-swift-codable

开源协议:MIT License

下载


Sample Swift Codable

Swift Codable Sample 입니다.

Codable

  1. Type Alias
  2. Codable
  3. A type that can convert itself into and out of an external representation.
  4. Declaration
  5. typealias Codable = Decodable & Encodable
  6. Discussion
  7. 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.

이라 설명이 되어있습니다.

  1. Codable Type Alias 입니다.
  2. Codable
  3. 외부 표현으로 변환하거나 외부 표현으로 변환할 있는 유형입니다.
  4. 선언
  5. typealias Codable = Decodable & Encodable
  6. Discussion
  7. Codable Encodable Decodable 프로토콜의 typealias입니다.
  8. Codable 사용하면 프로토콜을 모두 준수해야 되지요.

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

설명이 잘 되어있는 링크

Sample Source

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

  1. struct SampleStructData01: Codable {
  2. let id: String
  3. let code: String
  4. var order: Int?
  5. var test: Int?
  6. }
  7. struct SampleStructData02: Codable {
  8. let code: String
  9. let data: SampleStructData02SubData
  10. struct SampleStructData02SubData: Codable {
  11. let id : String
  12. let code : String
  13. let order : Int
  14. }
  15. }
  16. struct SampleStructData03 : Codable {
  17. let id : String
  18. var code : String?
  19. var order : Int
  20. enum CodingKeys : String, CodingKey{
  21. case id
  22. case code
  23. case order = "order_test"
  24. }
  25. }
  26. struct SampleStructData04 : Codable {
  27. let id : String
  28. let code : String
  29. let order : Int
  30. }
  31. /// https://github.com/yonaskolb/Codability
  32. struct SampleAnyCodableData01 : Codable {
  33. let id : AnyCodable
  34. let code : String
  35. }
  1. struct SampleResponse { }
  2. /**
  3. {
  4. userId: 1,
  5. id: 1,
  6. title: "delectus aut autem",
  7. completed: false
  8. }
  9. */
  10. extension SampleResponse {
  11. struct todos: Codable {
  12. let userId:Int
  13. let id:Int
  14. let title: String?
  15. let completed:Bool?
  16. let testTrash:String?
  17. }
  18. }
  • ViewController.swift

    • func sampleStructData01()

      1. func sampleStructData01() {
      2. print("===============================")
      3. print("== \(#function)")
      4. let dataJsonString = """
      5. {
      6. "id": "test@gmail.com",
      7. "code": "abcdefg1234",
      8. "order": 1
      9. }
      10. """.data(using: .utf8)!
      11. let sample = try! JSONDecoder().decode(SampleStructData01.self, from: dataJsonString)
      12. print(sample)
      13. print("===============================\n\n")
      14. }
    • func sampleStructData02()

      1. func sampleStructData02() {
      2. print("===============================")
      3. print("== \(#function)")
      4. let dataJsonString = """
      5. {
      6. "code": "poiuytrewq",
      7. "data": {
      8. "id": "test@gmail.com",
      9. "code": "abcdefg1234",
      10. "order": 1
      11. }
      12. }
      13. """.data(using: .utf8)!
      14. let sample = try! JSONDecoder().decode(SampleStructData02.self, from: dataJsonString)
      15. print(sample)
      16. print("===============================\n\n")
      17. }
    • func sampleStructData03()

      1. func sampleStructData02() {
      2. print("===============================")
      3. print("== \(#function)")
      4. let dataJsonString = """
      5. {
      6. "id": "test@gmail.com",
      7. "code": "abcdefg1234",
      8. "order_test": 1
      9. }
      10. """.data(using: .utf8)!
      11. let sample = try! JSONDecoder().decode(SampleStructData03.self, from: dataJsonString)
      12. print(sample)
      13. print("===============================\n\n")
      14. }
      • func sampleStructData04()
      1. func sampleStructData02() {
      2. print("===============================")
      3. print("== \(#function)")
      4. let dataJsonString = """
      5. [
      6. {
      7. "id": "aaaa@gmail.com",
      8. "code": "1234567890",
      9. "order": 1
      10. },
      11. {
      12. "id": "bbbb@gmail.com",
      13. "code": "abcdefghijklmn",
      14. "order": 2
      15. }
      16. ]
      17. """.data(using: .utf8)!
      18. do {
      19. let sample = try JSONDecoder().decode([SampleStructData04].self, from: dataJsonString)
      20. print(sample)
      21. } catch {
      22. print(error)
      23. }
      24. print("===============================\n\n")
      25. }
    • func sampleAnyCodableData01()

      • Codable을 사용하면서 Any 타입이 필요할 때.. 쉽지 않습니다. 그래서 라이브러리를 하나 사용해 봤습니다.
      • https://github.com/yonaskolb/Codability

        1. func sampleAnyCodableData01() {
        2. print("===============================")
        3. print("== \(#function)")
        4. let dataJsonString = """
        5. [
        6. {
        7. "id": "aaaa@gmail.com",
        8. "code": "1234567890",
        9. },
        10. {
        11. "id": 1234,
        12. "code": "abcdefghijklmn",
        13. }
        14. ]
        15. """.data(using: .utf8)!
        16. do {
        17. let samples = try JSONDecoder().decode([SampleAnyCodableData01].self, from: dataJsonString)
        18. //
        19. _ = samples.enumerated().map { sample -> String in
        20. if sample.element.id.value is String {
        21. print("index \(sample.offset) : id.value is String")
        22. } else if sample.element.id.value is Int {
        23. print("index \(sample.offset) : id.value is Int")
        24. } else {
        25. print("index \(sample.offset) : id.value is ?")
        26. }
        27. return ""
        28. }
        29. print(samples)
        30. } catch {
        31. print(error)
        32. }
        33. print("===============================\n\n")
        34. }
    • func sampleRequest01()

      1. func sampleRequest01(){
      2. print("===============================")
      3. print("== \(#function)")
      4. let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
      5. URLSession.shared.dataTask(with: url!, completionHandler: {
      6. (data, response, error) in
      7. if let error = error {
      8. print("== \(error)")
      9. } else {
      10. print("== success")
      11. guard let data = data else {
      12. return
      13. }
      14. do {
      15. let codableStruct = try JSONDecoder().decode(SampleResponse.todos.self, from: data)
      16. print("\(codableStruct)")
      17. print("== id : \(codableStruct.id)")
      18. } catch {
      19. print("== err in codable")
      20. }
      21. print("===============================\n\n")
      22. }
      23. }).resume()
      24. }

Result Log

  1. ===============================
  2. == sampleStructData01()
  3. SampleStructData01(id: "test@gmail.com", code: "abcdefg1234", order: Optional(1), test: nil)
  4. ===============================
  5. ===============================
  6. == sampleStructData02()
  7. SampleStructData02(code: "poiuytrewq", data: JWSCodableSample.SampleStructData02.SampleStructData02SubData(id: "test@gmail.com", code: "abcdefg1234", order: 1))
  8. ===============================
  9. ===============================
  10. == sampleStructData03()
  11. SampleStructData03(id: "test@gmail.com", code: Optional("abcdefg1234"), order: 1)
  12. ===============================
  13. ===============================
  14. == sampleStructData04()
  15. [JWSCodableSample.SampleStructData04(id: "aaaa@gmail.com", code: "1234567890", order: 1), JWSCodableSample.SampleStructData04(id: "bbbb@gmail.com", code: "abcdefghijklmn", order: 2)]
  16. ===============================
  17. ===============================
  18. == sampleRequest01()
  19. == success
  20. todos(userId: 1, id: 1, title: Optional("delectus aut autem"), completed: Optional(false), testTrash: nil)
  21. == id : 1
  22. ===============================