ios 在swift 4中创建一个包含数组和字典的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45810587/
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
create a dictionary contains Array and Dictionary in swift 4
提问by Vinod Radhakrishnan
I just want to create an API JSON Structure. The following are the post body keys and objects. Are there any methods like object with keys and values similar to Objective C in Swift 4?
我只想创建一个 API JSON 结构。以下是帖子正文键和对象。有没有类似于 Swift 4 中的 Objective C 的键和值的对象之类的方法?
{
"name": "switch 1",
"type": "Switch",
"gatewayId":515,
"serialKey": "98:07:2D:48:D3:56",
"noOfGangs": 4,
"equipments": [
{
"name": "light",
"type": "Light",
"port": "1"
},
{
"name": "television",
"type": "Television",
"port": "3"
}
]
}
回答by vadian
You can create the dictionary literally by annotating the type and replace the curly braces with square brackets
您可以通过注释类型并用方括号替换花括号来逐字创建字典
let dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [[ "name": "light", "type": "Light", "port": "1" ], ["name": "television", "type": "Television", "port": "3" ]]]
Or build it:
或者构建它:
var dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4]
var equipments = [[String:String]]()
equipments.append(["name": "light", "type": "Light", "port": "1" ])
equipments.append(["name": "television", "type": "Television", "port": "3" ])
dict["equipments"] = equipments
回答by Abdelahad Darwish
how to create Dictionary
如何创建字典
var populatedDictionary = ["key1": "value1", "key2": "value2"]
this how to create Array
这是如何创建数组
var shoppingList: [String] = ["Eggs", "Milk"]
you can create Dictionary by this type
您可以通过这种类型创建字典
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
// anather example
// 另一个例子
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
your JSON
你的 JSON
let dic :[String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [ [ "name": "light", "type": "Light", "port": "1" ],
[ "name": "television", "type": "Television", "port": "3" ] ] ]