gpt4 book ai didi

arrays - 从单例创建一个通用数组

转载 作者:搜寻专家 更新时间:2023-10-31 22:38:05 25 4
gpt4 key购买 nike

我想用我的代码将我的数组变成通用的。说到泛型,我是新手。

这是我的代码:

class APIServices {
static let youtubeBaseURL = "https://www.googleapis.com/youtube/v3/search"

static let shared = APIServices()

func fetchVideo(name: String, completionHandler: @escaping ([Item]) -> ()) {
let apiKey = "mykey"
let params = ["part": "snippet", "q": "tausiyah \(name)", "key": apiKey]

Alamofire.request(APIServices.youtubeBaseURL, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseData { (dataResponse) in
if let err = dataResponse.error {
print("Failed to get data:", err)
return
}
guard let data = dataResponse.data else { return }

do {
let youtubeData = try JSONDecoder().decode(YoutubeModel.self, from: data)

completionHandler(youtubeData.items)
} catch let decodeErr {
print("Failed to decode youtube data:", decodeErr)
}
}
}
}

这里是我的 YoutubeModel

struct YoutubeModel: Decodable {
var items: [Item]
}

struct Item: Decodable {
var id: VideoId
var snippet: Snippet
}

struct VideoId: Decodable {

var videoId: String

init(dictionary: [String: Any]) {
self.videoId = dictionary["videoId"] as? String ?? ""
}
}

struct Snippet: Decodable {

func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: "titleStringKey")
}

var title: String
}

completionHandler: @escaping ([item]) 中,我想将其变成泛型。如何更改 JSONDecoder 下面的 completionHandler?

最佳答案

您可以尝试下面的通用实现,

public class YoutubeModel<T: Decodable>: Decodable {

public var items: [T] = []
}

class APIServices {
static let youtubeBaseURL = "https://www.googleapis.com/youtube/v3/search"

static let shared = APIServices()

func fetchVideo<T: Decodable>(name: String, of type: T.Type, completionHandler: @escaping ([T]) -> ()) {
let apiKey = "mykey"
let params = ["part": "snippet", "q": "tausiyah \(name)", "key": apiKey]

Alamofire.request(APIServices.youtubeBaseURL, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseData { (dataResponse) in
if let err = dataResponse.error {
print("Failed to get data:", err)
return
}
guard let data = dataResponse.data else { return }

do {
let youtubeData = try JSONDecoder().decode(YoutubeModel<T>.self, from: data)

completionHandler(youtubeData.items)
} catch let decodeErr {
print("Failed to decode youtube data:", decodeErr)
}
}
}
}

用法

APIServices.shared.fetchVideo(name: "name", of: Item.self) { list in
print(list)
}

关于arrays - 从单例创建一个通用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com