繁体   English   中英

Swift 4 @转义类型作为参数

[英]Swift 4 @escaping type as parameter

我具有以下向服务器发出GET请求的功能。 问题是,我需要提供特定的struct类型Codable为类型@escaping 然后,我对JSONDecoder使用相同的类型,以将从JSON接收的数据解码为Video类型。

如何为该函数提供类型作为参数。 我想提供。 例如USER类型或CAR类型

    struct Video: Codable {
        var title: String
        var pretty_artists: String
        var yt_id: String
        var views: String
        var video_name: String
        var published: Published
        var result: Bool

        init(title: String = "", pretty_artists: String = "", yt_id: String = "", views: String = "", video_name: String = "", published: String = "", result: Bool = true) {
            self.title = title
            self.pretty_artists = pretty_artists
            self.yt_id = yt_id
            self.views = views
            self.video_name = video_name
            self.published = Published()
            self.result = result
        }
    }

//另一个文件

class XHR {

    // Video to be Dynamic
    func makeGetCall(todoEndpoint: String, completionHandler: @escaping (Video?, Error?) -> Void) {

        // code
        let decoder = JSONDecoder()

        do {
            let todo = try decoder.decode(Video.self, from: responseData)
            completionHandler(todo, nil)
        } catch {
            print("error trying to convert data to JSON")
            print(error)
            completionHandler(nil, error)
        }

    }
   }

//在这里,我将函数称为“ ViewController.swift”

    // Initial request
xhr.makeGetCall<XHR>(todoEndpoint: "https://kida.al/search/uh/onajr", { result, err  in
    if(result != nil) {
        self.ytPlayer.load(withVideoId: result!.yt_id, playerVars: self.playerVars)
        self.updateVideo(data: result!)
    }
})

您应该使用泛型。 只需将Video替换为符合Codable协议的通用参数Codable 就是这样。

func makeGetCall<T>(todoEndpoint: String, completionHandler: @escaping (T?, Error?) -> Void) where T: Codable {
    // As step one, you need to do networking to fetch `responseData`

    // code
    let decoder = JSONDecoder()

    do {
        let todo = try decoder.decode(T.self, from: responseData)
        completionHandler(todo, nil)
    } catch {
        print("error trying to convert data to JSON")
        print(error)
        completionHandler(nil, error)
    }
}

用法

在第一个参数之后声明类型。

makeGetCall(todoEndpoint: "/path/to/resource") { (video: Video?, error) in

}

您的用法

class XHR {

enum Result<T> {
    case success(T)
    case failure(Error)
}

func makeGetCall<T>(todoEndpoint: String, completionHandler: @escaping (Result<T>) -> Void) where T: Codable {

    // code
    let decoder = JSONDecoder()

    do {
        let todo = try decoder.decode(T.self, from: responseData)
        completionHandler(.success(todo))
    } catch {
        print("error trying to convert data to JSON")
        print(error)
        completionHandler(.failure(error))
    }

}
}

// Initial request

let xhr = XHR()
xhr.makeGetCall(todoEndpoint: "https://kida.al/search/uh/onajr") { (result: XHR.Result<Video>) in
    switch result {
    case .failure(let error):
        // Ups, there is something wrong
        print(error)
    case .success(let video):
        // Sal goodman
        self.ytPlayer.load(withVideoId: video.yt_id, playerVars: self.playerVars)
        self.updateVideo(data: video)
    }
}

您可以从此json为所需的任何对象创建模型类:

class User {
    let userId: String?
    let userName: String?

    init(jsondata: JSON?) {
        self.userId = jsondata?["user_id"].stringValue
        self.userName = jsondata?["user_name"].stringValue  
    }
}

然后创建此模型的对象:

func makeGetCall(todoEndpoint: String, completionHandler: @escaping (User?, Error?) -> Void) {

    // code
    let decoder = JSONDecoder()

    do {
        let todo = User(responsedata)
    } catch {
        print("error trying to convert data to JSON")
        print(error)
        completionHandler(nil, error)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM