Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dictionary to array in swift

Tags:

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
        )

)
like image 791
Janusz Kubala Avatar asked Feb 17 '16 09:02

Janusz Kubala


People also ask

How is dictionary array in Swift?

Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you can't insert a value of the wrong type into a collection by mistake.

Can an array contain a dictionary?

An array in Swift can contain any type of data, values types as well as reference types. The type of data an array stores can sometimes be quite complex, though.

What is a dictionary in Swift?

In swift, a dictionary is a collection of key-value pairs. We can use any type of data as a key and any type of data as a value. We can create a dictionary using the (key:value) syntax. A key should always be a single item. But a value can be a single item or a collection of items, like an array or a dictionary.


1 Answers

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)")
like image 56
Greg Avatar answered Sep 27 '22 22:09

Greg