Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a dictionary contains Array and Dictionary in swift 4

I just want to create an API JSON Structure. The following are the post body keys and objects. Are there any methods like 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"
        }
    ]
}
like image 457
Vinod Radhakrishnan Avatar asked Aug 22 '17 06:08

Vinod Radhakrishnan


1 Answers

You can create the dictionary literally by annotating the type and replace the curly braces 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
like image 71
vadian Avatar answered Oct 24 '22 13:10

vadian