繁体   English   中英

在swift 4中创建一个包含Array和Dictionary的字典

[英]create a dictionary contains Array and Dictionary 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"
        }
    ]
}

您可以通过注释类型来逐字地创建字典,并使用方括号替换花括号

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" ]]]

或构建它:

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

如何创建字典

var populatedDictionary = ["key1": "value1", "key2": "value2"]

这个如何创建数组

var shoppingList: [String] = ["Eggs", "Milk"]

你可以用这种类型创建Dictionary

var dictionary =  [Int:String]() 

dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)

// anather例子

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)

你的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" ] ] ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM