我正在使用 Xcode 8.3.3 。我收到 Swift 编译器错误“对成员的不明确引用”。我已经完成了代码,似乎无法弄明白。
protocol APIClient {
var session: URLSession { get }
func fetch<T: JSONDecodable>(with request: URLRequest, parse: @escaping (JSON) -> T?, completion: @escaping (Result<T, APIError>) -> Void)
func fetch<T: JSONDecodable>(with request: URLRequest, parse: @escaping (JSON) -> [T], completion: @escaping (Result<[T], APIError>) -> Void)
}
fetch(with: request, parse: { json -> [YelpBusiness] in
guard let businesses = json["businesses"] as? [[String: Any]] else { return [] }
return businesses.flatMap { YelpBusiness(json: $0) }
}, completion: completion)
答案 0 :(得分:0)
我检查了你的代码。您已创建protocol
来确认班级YelpClient
。怎么了?
fetch(with: request, parse: { json -> [YelpBusiness] in
guard let businesses = json["businesses"] as? [[String: Any]] else { return [] }
return businesses.flatMap { YelpBusiness(json: $0) }
}, completion: completion)
使用上面的代码,您可以直接拨打protocol
而无需任何delegate
。问题是您需要继承protocol
类中的YelpClient
,如下所示。
func fetch<T>(with request: URLRequest, parse: @escaping (APIClient.JSON) -> T?, completion: @escaping (Result<T, APIError>) -> Void) where T : JSONDecodable {
//Code
}
func fetch<T>(with request: URLRequest, parse: @escaping (APIClient.JSON) -> [T], completion: @escaping (Result<[T], APIError>) -> Void) where T : JSONDecodable {
//Code
}
有关详细信息,请参阅apple documentation
更新:
查看以下屏幕截图以获得更好的想法