Janusz Kubala
Janusz Kubala

Reputation: 401

How to add dictionary to array in swift

How to initialize and add values to array following data

(
    [0] => Array
        (
            [name] => First element
            [foo] => bar
        )

    [1] => Array
        (
            [name] => Second element
            [foo] => bar2
        )

)

Upvotes: 6

Views: 19184

Answers (1)

Greg
Greg

Reputation: 25459

That's array which contains dictionaries, Is it what you are after?

let myArray = [["name": "First element", "foo": "bar"], ["name": "Second element", "foo": bar2]]

// Edited add items in loop:

var myArray = [[String: String]]()
for i in 0..<10 {

    let dict = ["name": "Item\(i)", "foo": "bar\(i)"]
    myArray.append(dict)
}
print("\(myArray)")

Upvotes: 17

Related Questions