代码之家  ›  专栏  ›  技术社区  ›  iKK

解码Swift中的可编码文件

  •  0
  • iKK  · 技术社区  · 7 年前

    在实现这一点时遇到困难:我试图将JSON解码抽象为一个函数,将Codable和一些数据作为参数。

    因此,如果可能,我需要有以下函数签名:

    func doTheJSONDecoding(cdbl: Codable, data: Data) {...}

    这是我的代码,从数据模型开始。下面有两个例子。。。。

    import UIKit
    import Foundation
    
    struct MyStructCodable : Codable {
        let items : [MyValue]?
    }
    
    struct MyValue : Codable {
        let value : String?
    }
    
    let dta: Data = """
    {
      "items": [
        {
          "value": "Hello1"
        }
      ]
    }
    """.data(using: .utf8)!
    

    然后是两个例子:

    // Example 1: this code works fine !!!!!!!!!!!!!!!!!!!!!!!!
    
    let decoder = JSONDecoder()
    do {
        let result = try decoder.decode(MyStructCodable.self, from: dta)
        print(result.items?[0].value ?? "")
    } catch {
        print(error)
    }
    
    // above code prints:   Hello1
    
    
    // Example 2: this code does not work - WHY ???????????????
    
    func doTheJSONDecoding(cdbl: Codable, data: Data) {
        let decoder = JSONDecoder()
        do {
            let result = try decoder.decode(cdbl, from: data)
            print(result.items?[0].value ?? "")
        } catch {
            print(error)
        }
    }
    
    let myValue = MyValue(value: "Hello2")
    let myStructyCodable = MyStructCodable(items: [myValue])
    doTheJSONEncoding(cdbl: myStructyCodable, data: dta)
    

    enter image description here

    有什么方法可以保留函数签名(即。 func doTheJSONDecoding(cdbl: Codable, data: Data)

    1 回复  |  直到 7 年前
        1
  •  2
  •   Joakim Danielson    7 年前

    这是我试图让你的函数工作,它可能会得到改进,但它确实返回一个正确解码的对象。注意,它采用object类型,而不是object类型,并且实现可解码的是类型T。

    func doTheJSONEncoding<T: Decodable>(cdbl: T.Type, data: Data) -> T? {
        let decoder = JSONDecoder()
        do {
            let result = try decoder.decode(cdbl.self, from: data)
            return result
        } catch {
            print(error)
        }
        return nil
    }
    
    //testing it
    let myValue = MyValue(value: "Hello2")
    let myStructyCodable = MyStructCodable(items: [myValue])
    let decoded = doTheJSONEncoding(cdbl: MyStructCodable.self, data: dta)
    print(decoded?.items?[0].value ?? "")