Search code examples
swiftnsarrayconvertersnsdictionary

Convert NSARRAY to NSDictionary to be used as a result of JSon serialisation swift4 Xcode 9


I want to convert a NSArray to a NSDictionary and thereafter choose the keys and the values in the NSDictionary to be able to later on add the data from the NSDictionary to a object by using the keys in it.

How can I do this in the smartest way?

Here's what I have so far:

func makeCall(completion: result: NSDictionary or Dictionary){
    let json = try JSONSerialization.jsonObject(with: data!, options:  JSONSerialization.ReadingOptions(rawValue: 0)) as? NSDictionary
    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Array<Any>
}

The two JSON files look nearly the same. The difference is the var type so you will get keys and values but in an array style. We need it in a dictionary style to get the values by their keys.


Solution

  • Swift 4

    In Swift you should rather use Dictionary, and only use NSDictionary if you explicitly need that type.

        //your NSArray
        let myArray: NSArray = ["item1","item2","item3"]
    
        //initialize an emtpy dictionaty
        var myDictionary = [String:String]()
    
        //iterate through the array
        for item in myArray
        {
            //add array items to dictionary as key with any value you prefer
            myDictionary.updateValue("some value", forKey: item as! String)
        }
    
        //now you can use myDictionary as Dictionary
        print ("my dictionary: ")
        print (myDictionary)
    
        //if you prefer to use it as an NSDictionary
        let myNSDictionary = myDictionary as NSDictionary!
        print ("my NSDictionary: ")
        print (myNSDictionary)