0 converter nsdictionary nsarray swift
我想将 a 转换NSArray为 a 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>
}
Run Code Online (Sandbox Code Playgroud)
这两个 JSON 文件看起来几乎相同。不同之处在于 var 类型,因此您将获得数组样式的键和值。我们需要它在字典样式中通过它们的键来获取值。
小智 5
斯威夫特 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3966 次 |
| 最近记录: |