Jack Amoratis Jack Amoratis - 1 year ago 113
Swift Question

How to append associative array elements in Swift

How do I create and append to an associative array in Swift? I would think it should be something like the following (note that some values are strings and others are numbers):

var myArray = []

var make = "chevy"
var year = 2008
var color = "red"


The goal is to be able to have an array full of results where I can make a call such as:

println(myArray[0]["trackMake"]) //and get chevy
println(myArray[0]["trackColor"]) //and get red

Answer Source

Simply like this:


Add the brackets. This will make it a hash and append that to the array.

In such cases make (extensive) use of let:

let dict  = ["trackMake":make,"trackYear":year,"trackColor":color]

The above assumes that your myArray has been declared as

var myArray = [[String:AnyObject]]()

so the compiler knows that it will take dictionary elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download