Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append associative array elements in Swift

Tags:

ios

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"

myArray.append("trackMake":make,"trackYear":year,"trackColor":color)

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
like image 536
Jack Amoratis Avatar asked Apr 26 '26 06:04

Jack Amoratis


1 Answers

Simply like this:

myArray.append(["trackMake":make,"trackYear":year,"trackColor":color])

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]
myArray.append(dict)

The above assumes that your myArray has been declared as

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

so the compiler knows that it will take dictionary elements.

like image 101
qwerty_so Avatar answered Apr 28 '26 21:04

qwerty_so