func downloadCurrentWeather(completed: @escaping DownloadComplete){
Alamofire.request(API_URL).responseJSON { (response) in
let result = response.result
let json = JSON(result.value) // <-- (EXPRESSION IMPLICITLY COERCED WARNING)
self._cityName = json["name"].stringValue
let tempDate = json["dt"].double
let convertedDate = Date(timeIntervalSince1970: tempDate!)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: convertedDate)
self._date = "\(currentDate)"
self._weatherType = json["weather"][0]["main"].stringValue
let downloadedTemp = json["main"]["temp"].double
self._currentTemp = (downloadedTemp! - 273.15).rounded(toPlaces: 0)
completed()
}
}
答案 0 :(得分:2)
它强制它,因为value
是Any?
可选值。我建议您展开value
以确保它不是nil
:
func downloadCurrentWeather(completed: @escaping DownloadComplete){
Alamofire.request(API_URL).responseJSON { (response) in
guard let value = response.result.value else {
print(response.result.error ?? "Unknown error")
return
}
let json = JSON(value)
...
}
}
作为进一步的改进,我改变DownloadComplete
以包含有关其是否失败的信息。例如,我可能会添加Error?
参数,然后您可以执行以下操作:
func downloadCurrentWeather(completed: @escaping DownloadComplete){
Alamofire.request(API_URL).responseJSON { (response) in
guard let value = response.result.value else {
completed(response.result.error)
return
}
let json = JSON(value)
...
completed(nil)
}
}
然后,来电者可以看到error
是否nil
。
另一种方法是switch
上的response.result
,因为在.success
情况下,您可以使用相关的值:
func downloadCurrentWeather(completed: @escaping DownloadComplete){
Alamofire.request(API_URL).responseJSON { response in
switch response.result {
case .failure(let error):
completed(error)
case .success(let value):
let json = JSON(value)
...
completed(nil)
}
}
}