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()
    }
}

最佳答案

它是强制的,因为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)
        }
    }
}

关于ios - “表达被隐式强制”警告是什么意思?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49434906/

10-14 16:59