在Swift 4中创建一个包含数组和字典的字典。

9

我希望创建一个API JSON结构。以下是post body的键和对象。在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"
        }
    ]
}

你可以为所有参数使用一个字典,其中你可以为“equipments”参数之一使用一个数组,并将该数组设置为该键的对象。 - Pankaj K.
你有没有想到解决这个问题的办法?我正在尝试创建一个空的嵌套字典,但是我真的很困难。这两个答案都没有帮助我。我正在从Python 3.8转移到XCode 11.5,学习曲线陡峭,需要弄清楚如何在XCode中完成我在Python中所做的事情。 - SouthernYankee65
2个回答

10
你可以通过注释类型并用方括号替换花括号,来直接创建字典。
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

8
如何创建字典
var populatedDictionary = ["key1": "value1", "key2": "value2"]

这是如何创建数组:

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

您可以使用这种类型创建字典。
var dictionary =  [Int:String]() 

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

// 另一个例子

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

所有这些值在声明时都被初始化。我该如何全局声明一个字典,并在按钮操作或函数中添加多个值到字典中? - Vinod Radhakrishnan
所以你需要可变字典还是什么? - Abdelahad Darwish
有可变字典吗?在Swift 3.1中是否有类似于“NsDictionary DictionaryWithObjectsandKeys”的函数,以便我可以在单行中添加多个值到字典中。感谢您的帮助。 :) - Vinod Radhakrishnan
回答已更新,请检查。dictionary.updateValue(value: "Hola", forKey: 1) - Abdelahad Darwish
它仅适用于更新单个键值对。我的用例是 GlobalDictionary //在类中声明 通过按钮点击操作将值设置到globalDictionary中//添加多个键值对字符串、字典数组、整数等。 - Vinod Radhakrishnan
我必须将这种参数字典作为POST请求发送。我已经准备好发送了。收到成功的响应,但在后端中所有参数都显示为空。不知道发生了什么。 - Protocol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接