【发布时间】:2021-12-15 03:46:15
【问题描述】:
我正在尝试将我的工作完成处理函数转换为新的 async/await 语法,但是我在为使用通用参数 (T) 的函数找到正确的语法时遇到了问题:
我以前用过的和有效的:
typealias CurrentWeatherCompletionHandler = (CurrentWeather?, Error?) -> Void
private func weatherDownload<T: Codable>(weatherType: String, completionHandler completion: @escaping (_ object: T?,_ error: Error?) -> ()) {
let storage = Storage.storage()
let pathReference = storage.reference(withPath: "\(weatherType)"+"-de.json")
pathReference.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("Error beim \(weatherType) Download: \(error)")
completion(nil, error)
} else {
do {
let weather = try self.decoder.decode(T.self, from: data!)
completion(weather, nil)
} catch let error {
completion(nil, error)
}
}
}
}
func getCurrentWeather(completionHandler completion: @escaping CurrentWeatherCompletionHandler) {
weatherDownload(weatherType: Constants.currentWeatherFolder) { (weather: CurrentWeather?, error) in
completion(weather, error)
}
}
我试过了,但没用:
private func weatherDownload<T: Codable>(weatherType: String) async -> (weather: T?, error: Error?) {
//same network code as before but with return instead of completion:
return (weather, nil) // Compiler Error: 'nil' requires a contextual type / Unexpected non-void return value in void function
}
func getCurrentWeather() async -> (weather: CurrentWeather?, error: Error?) {
return await weatherDownload(weatherType: Constans.currentWeatherFolder)
}
欢迎提出任何想法。
【问题讨论】:
-
请在异步函数中附上您的网络逻辑的完整代码。
-
我的猜测是您没有将“与以前相同的网络代码”转换为异步。
-
感谢您的反馈。我附上了上面的网络代码。它从 FirebaseStorage 加载数据。我找不到 getData() 的异步函数。
-
编译失败的函数中
weather和T是什么关系?
标签: swift firebase firebase-storage