ios swift:向 NSDictionary 添加多个 <key, value> 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27045887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
swift: Add multiple <key, value> objects to NSDictionary
提问by Srujan Simha
I'm trying to add multiple objects to NSDictionary, like
我正在尝试向 NSDictionary 添加多个对象,例如
var myDict: NSDictionary = [["fname": "abc", "lname": "def"], ["fname": "ghi", "lname": "jkl"], ...]
Is it even possible to do this? If not, please suggest a better way. I actually need to convert this NSDictionary to JSON string and send that to the server, so I need multiple objects in NSDictionary.
甚至有可能做到这一点吗?如果没有,请提出更好的方法。我实际上需要将此 NSDictionary 转换为 JSON 字符串并将其发送到服务器,因此我需要 NSDictionary 中的多个对象。
回答by dasblinkenlight
You can definitely make a dictionary of dictionaries. However, you need a different syntax for that:
你绝对可以制作字典字典。但是,您需要不同的语法:
var myDictOfDict:NSDictionary = [
"a" : ["fname": "abc", "lname": "def"]
, "b" : ["fname": "ghi", "lname": "jkl"]
, ... : ...
]
What you have looks like an arrayof dictionaries, though:
不过,您所拥有的看起来像是一系列字典:
var myArrayOfDict: NSArray = [
["fname": "abc", "lname": "def"]
, ["fname": "ghi", "lname": "jkl"]
, ...
]
To get JSON that looks like this
获得看起来像这样的 JSON
{"Data": [{"User": myDict1}, {"User": myDict1},...]}
you need to add the above array to a dictionary, like this:
您需要将上述数组添加到字典中,如下所示:
var myDict:NSDictionary = ["Data" : myArrayOfDict]
回答by Jaydip
SWIFT 3.0
斯威夫特 3.0
- List item
- 项目清单
Frist of all you can create NSArray and Then you can Set Array in NSMutableDictionary using setvalue(forKey:)
default method.
首先,您可以创建 NSArray,然后您可以使用setvalue(forKey:)
默认方法在 NSMutableDictionary 中设置数组。
var arrFname : NSArray!
arrFname = ["abc","xyz","mno"]
var arrLname : NSArray!
arrFname = ["tuv","xuv","swift"]
var dicSet : NSMutableDictionary!
dicSet.setObject(arrFname, forKey : "Fname")
dicSet.setObject(arrLname, forKey : "Lname")
print(dicSet)
回答by saurabh rathod
var tempDict = NSMutableDictionary()
tempDict.setValue("sam", forKey : "one")
print(tempDict["one"] ?? "1")