[iOS] Could not cast value of type ‘__NSCFNumber’ to ‘NSString’

Posted in :

json 長醬子:

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

直接用 String 去存取  “AUD” 欄位,會出錯,解法是用 Float 或Double去接浮點數,如果需要轉成 String 就用 String 包起來:

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

You can convert it in string like,

let aud : String = String(rateDict["AUD"])

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *