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

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

我想将 NSArray 转换为 NSDictionary,然后选择 NSDictionary 中的键和值,以便稍后从 [=] 添加数据14=] 通过使用其中的键到一个对象。

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

这是我目前的情况:

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 类型,因此您将获得数组样式的键和值。我们需要它以字典形式通过键获取值。

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)