我想用我的代码将数组转换为通用数组。关于泛型,我是新手。
这是我的代码:
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?
答案 0 :(得分:2)
您可以尝试以下通用实现,
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)
}