How to initialize and add values to array following data
(
[0] => Array
(
[name] => First element
[foo] => bar
)
[1] => Array
(
[name] => Second element
[foo] => bar2
)
)
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.
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.
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.
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)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With