Search code examples
jsonswiftcastingnsdictionary

Could not cast value of type '__NSCFNumber' (0x1105dc3c0) to 'NSString' Swift 3


This is my url response

{
"base": "EUR",
"date": "2017-05-16",
"rates": {
    "AUD": 1.492,
}}

And this is my code

Alamofire.request("http://api.fixer.io/latest").responseJSON { response in
        guard let JSON = response.result.value else{
            print("Error")
            return
        }
            print("JSON: \(JSON)")
        let dict = JSON as! NSDictionary
        let base : String = dict["base"] as! String
        print("Base:", base)
        let date : String = dict["date"] as! String
        print("Date:", date)
        let rateDict = dict["rates"] as! NSDictionary
        let aud : String = rateDict["AUD"] as! String
        print("AUD:", aud)
    }

In Line let aud : String = rateDict["AUD"] as! String there is error with message as mentioned above in title. What's happening here. Please anyone help me.


Solution

  • It's a floating point not a string. cast is to float

    let aud = rateDict["AUD"] as! Float
    

    Edit: Avoid force casting, as that may crash your app if the data is not expected. Using code below will prevent crashes

    if let rateDict = dict["rates"] as? [String : Any] {
        if let aud = rateDict["AUD"] as? Float {
            print("\(aud)")
        }
    }