Search code examples
swiftnsarraynsdictionaryswift2

How to use Arrays em Dictionaries for create a object (like js) in Swift


I'm trying to get some iPhone data to my database on my site. But the data I need to send by create one object(like a JS) - with Arrays and Dictionaries, for json. The example of "object":

var data = {
    itens: {
       [id: "123", name: "Watch"], 
       [id: "321", name: "iPhone"],
       [id: "213", name: "iMac"] 
    },
    show: {
        bar: 1,
        aside: 1,
        footer:0,
        main:0
    }
}

I am a developer Javascript, and recently fell in love with Apple Swift.

My question is: How do I create an "object", as in the example above, in Swift?.


Solution

  • You want to create a dictionary where the key is a String and the value is something else, so:

    let data : [String: Any] = [
        "items": [
            ["id": "123", "name": "Watch"],
            ["id": "321", "name": "iPhone"],
            ["id": "213", "name": "iMac"]
        ],
        "show": ["bar": 1, "aside": 1, "footer": 0, "main": 0]
    ]