Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - Swift: Could not cast value of type '__NSCFArray' to 'NSDictionary'

I have JSON data from website. I made the main dictionary and I can parse every data except one sub dictionary. I get the error "Swift: Could not cast value of type '__NSCFArray' to 'NSDictionary'"

This example of my data. I cannot parse "weather" but I can parse all other dictionaries like "wind".

   ["name": Mountain View, "id": 5375480, "weather": (
        {
        description = "sky is clear";
        icon = 01n;
        id = 800;
        main = Clear;
    }
), "base": cmc stations, "wind": {
    deg = "129.502";
    speed = "1.41";

Snippet of code

 let windDictionary = mainDictionary["wind"] as! [String : AnyObject
 let speed = windDictionary["speed"] as! Double
 print(speed)
 let weather = mainDictionary["weather"] as! [String : AnyObject]
 print(weather)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

on behalf your comment...I would say windDictionary is Dictionary...

Dictionary denotes in JSON with {} and 
Array denotes with [] // In printed response you may have array with ()

So, your weather part is Array of Dictionary...You have to parse it like

 let weather = mainDictionary["weather"] as! [[String : AnyObject]]  // although please not use force unwrap .. either use `if let` or `guard` statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...