【问题标题】:create a dictionary contains Array and Dictionary in swift 4在swift 4中创建一个包含数组和字典的字典
【发布时间】:2018-01-30 07:46:42
【问题描述】:

我只想创建一个 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"
        }
    ]
}

【问题讨论】:

  • 您可以为其中的所有参数获取一个字典,您可以为其中一个参数“设备”获取一个数组,并将该数组设置为该键的对象。
  • 您有没有为此提出过解决方案?我正在尝试创建一个空的嵌套字典,我真的很挣扎。这些答案都没有帮助我。我正在从 Python 3.8 迁移到 XCode 11.5,要弄清楚如何在 XCode 中完成我在 Python 中所做的事情,这是一个陡峭的学习曲线。

标签: ios json swift nsarray nsdictionary


【解决方案1】:

如何创建字典

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

【讨论】:

  • 所有这些值都是在声明时初始化的。如何全局声明字典并在按钮操作或函数中将多个值添加到字典中?
  • 所以你需要可变字典还是什么?
  • 是可变字典。 swift 3.1中是否有类似“NsDictionary DictionaryWithObjectsandKeys”的功能。所以我可以在一行中将多个值添加到字典中。感谢你的帮助。 :)
  • 答案更新检查它 dictionary.updateValue(value: "Hola", forKey: 1)
  • 它仅适用于更新单个键值对。我的用例是 GlobalDictionary //在类中声明,通过按钮单击操作将值设置到 globalDictionary //添加多个键值对字符串、字典数组、整数等。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2019-03-17
    相关资源
    最近更新 更多