Create Dictionary Contains Array and Dictionary in Swift 4

I just want to create the JSON Structure API. Listed below are keys and post-body objects. Are there any methods like an object with keys and values ​​similar to Objective-C in 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" } ] } 
+5
source share
3 answers

Finally, I found what I need. Swift 4/3 provides a built-in function for adding multiple objects and keys to a dictionary.

myGlobalDictionary = NSMutableDictionary.init (objects: ["Obj1", "Obj2"], forKeys: ["key1"] as NSCopying, "key2" as NSCopying])

Happy coding :)

+1
source

You can create a dictionary literally by annotating the type and replacing curly brackets with square brackets

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

Or build it:

 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 
+1
source

how to create a dictionary

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

this is how to create an array

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

you can create a dictionary of this type

 var dictionary = [Int:String]() dictionary.updateValue(value: "Hola", forKey: 1) dictionary.updateValue(value: "Hello", forKey: 2) dictionary.updateValue(value: "Aloha", forKey: 3) 

// anatron example

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

your 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" ] ] ] 
+1
source

Source: https://habr.com/ru/post/1271091/


All Articles