条件绑定的初始化程序必须具有可选类型,而不是'[String:Any]'

时间:2017-06-29 14:58:05

标签: swift swift3 alamofire optional-parameters

谁能告诉我如何解决这个问题?我只是试图从事情中接收信号。

   `self.title = "Home"
    print("Requesting data...")
    Alamofire.request( "https://api.thingspeak.com/channels/290427/feeds.json", parameters: ["results": "1", "location": "false"]) // Gets the latest info from ThingSpeak
        .responseJSON { response in

            print("Data downloaded: \(response.result)")
            if let json = response.result.value as! [String:Any] {
                print(json) //see full data

                if let feeds = json["feeds"] as? [String: Any] {

                    for feed in feeds {
                        print(feed["field2"])
                        if let temperatureStr = feed["field2"] as? String, let dateStr = feed["created_at"] as? String {
                            if let temperature = Double(temperatureStr){
                                self.label.text = "Temperature: \(temperature)°F" //Displays last updated data entry

                            }

错误在行

if let json = response.result.value as! [String:Any] {

错误消息显示“条件绑定的初始化程序必须具有可选类型,而不是'[String:Any]'

2 个答案:

答案 0 :(得分:4)

如果您想使用条件绑定,表达式的右侧应该是可选的。

改变这个:

if let json = response.result.value as! [String:Any]

对此:

if let json = response.result.value as? [String:Any]

答案 1 :(得分:1)

该消息意味着您需要具有可选类型,因此只需更改

if let json = response.result.value as! [String:Any] {

if let json = response.result.value as? [String:Any] {