web-dev-qa-db-ja.com

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

タイプに注釈を付けることで文字通り辞書を作成し、中括弧を角括弧で置き換えることができます

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
vadian

辞書の作り方

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