将NSARRAY转换为NSDictionary以用作JSon序列化的结果swift4 Xcode 9

时间:2018-02-02 09:19:17

标签: swift nsarray converter nsdictionary

我想将NSArray转换为NSDictionary,然后选择NSDictionary中的键和值,以便稍后可以添加NSDictionary中的数据通过使用其中的键来对象。

我怎样才能以最聪明的方式做到这一点?

这是我到目前为止所拥有的:

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>
}

两个JSON文件看起来几乎相同。区别在于var类型,因此您将获得键和值,但采用数组样式。我们需要它以字典样式来获取键的值。

1 个答案:

答案 0 :(得分:3)

Swift 4

在Swift中,您应该使用Dictionary,并且只有在明确需要该类型时才使用NSDictionary。

    //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)