Swift 传递方法参数 Struct Decodable

Swift passing method params Struct Decodable

,Swift 4 如何在方法参数中传递 Decodable Struct 并在 JSONDecoder() 中解析它? 错误:

Cannot invoke 'decode' with an argument list of type '(Decodable, from: Data)'

struct JsonRespons: Codable {
    let uid: String
    let msisdn: String
    let APK: String
    let fname: String
    let lname: String
}

struct JsonResponsError: Decodable {
    let uid: String
    let error: String
}

extension UIView {

func phoneAuth(serverApi path:String, jsonStruct:Codable){
    let jsonUrlString = Globals.JOSN_API_URL + path
    guard let url = URL(string: jsonUrlString) else {
        return

    }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard err == nil else {
            return
        }

        guard let data = data else { return }

        do {
            let result = try JSONDecoder().decode(jsonStruct.self, from: data)
            self.handleJsonResult(resalt: result as AnyObject)

        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }

    }.resume()
}


    func handleJsonResult(resalt:AnyObject){
        print(resalt)
    }

}

添加Codable to the inheritance list for Landmark triggers an automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable:

您可以使用 Codable

struct Landmark: Codable {
    var name: String
    var foundingYear: Int

    // Landmark now supports the Codable methods init(from:) and encode(to:), 
    // even though they aren't written as part of its declaration.
}

替代解决方案是

func phoneAuth(serverApi path: String, Completion block: @escaping ((Data) -> ())) {

    URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in

        if let d = data {
            block(d)
        }
    }.resume()
}

调用方法

phoneAuth(serverApi: "yourUrl") { (data) in

    do {
        let result = try JSONDecoder().decode(YourDecodable.self, from: data)
    } catch let jsonErr {
        print("Error serializing json:", jsonErr)
    }
}

不用传参,可以像下面这样实现解码

extension UIView {

func phoneAuth(serverApi path:String){
    let jsonUrlString = Globals.JOSN_API_URL + path
    guard let url = URL(string: jsonUrlString) else {
        return

}

URLSession.shared.dataTask(with: url) { (data, response, err) in
    guard err == nil else {
        return
    }

    guard let data = data else { return }

    do {
        let result = try JSONDecoder().decode(JsonRespons.self, from: data)
        self.handleJsonResult(resalt: result as AnyObject)

    } catch let jsonErr {
        print("Error serializing json:", jsonErr)
    }

}.resume()
}