Initializer for conditional binding must have Optional type, not '[String : Any]'

社会主义新天地 提交于 2021-02-05 10:53:45

问题


Can anyone tell me how to fix this? Im just trying to receive signals from thing speak.

   `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

                            }

The error is in the line

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

Error message says "Initializer for conditional binding must have Optional type, not '[String : Any]'


回答1:


If you wanna use conditional binding, the right side of the expression should be optional.

Change this:

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

To this:

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



回答2:


That message mean that you need to have optional type so just change

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

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


来源:https://stackoverflow.com/questions/44828657/initializer-for-conditional-binding-must-have-optional-type-not-string-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!