What is difference between NSDictionary vs Dictionary in Swift?

后端 未结 4 1913
清歌不尽
清歌不尽 2021-02-18 12:52

I\'m learning Swift, and I can see Dictionary in it.
But there are lots of examples that are using NSDictionary with Swift.
What\'s the

4条回答
  •  走了就别回头了
    2021-02-18 13:29

    Consider this example

        let dataArray = NSMutableArray()
    
        let d0 = ["code":"AA","name":"American Airlines"]
        let d1 = ["code":"BA","name":"British Airlines"]
        let d2 = ["code":"DA","name":"Delta Airlines"]
    
        dataArray.addObject(d0)
        dataArray.addObject(d1)
        dataArray.addObject(d2)
    

    later...

    let d0 = dataArray.objectAtIndex(0) as! [String:String]
    let lbl = UILabel() 
    lbl.text = d0["code"] // no xcode warnings
    

    Using NSDictionary in swift

    let d0 = dataArray.objectAtIndex(0) as! NSDictionary 
    

    Now you need to coerce the dictionary value into shape.

    lbl1.text = d0["name"] as! String
    

    From experience - when dealing with json responses - I've used NSDictionary as it's loosely typed and I can't guaranteed to know exactly what it contains - just that is valid json. There's a growing library of native swift tools to handle this use case, I suggest looking here https://github.com/search?q=json+NSDictionary+swift&type=Code&utf8=%E2%9C%93

    In this case - you need to hack around data with the 'if let' dance.

    if let results = json["result"] as? NSDictionary
    

    lastly - NSMutableDictionary is more on par with Dictionary as you won't be able to mutate the key / value pairs on a NSDictionary.

    eg.

    results["code"] = 100 // <-- BOOM
    

    the work around -

    let mResults = NSMutableDictionary(dictionary:results)
    
    mResults["code"] = NSNumber(100) // <-- OK
    

    which begs the clarification - you can only stick NSObjects (NSNumbers / NSArrays / NSCount/NSSet) inside the NSMutableDictionaries. The Swift Dictionary gets around this.

提交回复
热议问题