Je veux juste créer une structure JSON API. Voici les clés et les objets du corps du message. Existe-t-il des méthodes comme objet avec des clés et des valeurs similaires à l'objectif C dans Swift 4?
{
"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"
}
]
}
Vous pouvez créer le dictionnaire littéralement en annotant le type et remplacer les accolades par des crochets
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" ]]]
Ou construisez-le:
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
comment créer un dictionnaire
var populatedDictionary = ["key1": "value1", "key2": "value2"]
comment créer un tableau
var shoppingList: [String] = ["Eggs", "Milk"]
vous pouvez créer un dictionnaire par ce type
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
// exemple anather
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
votre 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" ] ] ]