3

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
2
  • Do you want results like dictionary(key:value) in array? Commented May 25, 2015 at 12:01
  • When it's done, I am trying to get results such as: myArray[0]["trackMake"] //and get chevy Which means the zero could be replaced with any valid integer to refer to an array element Commented May 25, 2015 at 12:03

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

9 Comments

But when I try what you said I get an error: NSArray does not have a member named append. I am setting up the array like this: var myArray = []
@JackAmoratis Pls. show the declaration of your array.
You need to declare it as var myArray = [[String:AnyObject]]()
Thanks Thomas, and that declaration will also accomodate numerical items such as year?
Yes. You can put Int and String inside since they conform to the AnyObject protocol
|
3

I accept above answer.It is good.Even you have given correct answer,I like to give simplest way.The following steps are useful,if you guys follow that.Also if someone new in swift and if they go through this,they can easily understand the steps.

STEP 1 : Declare and initialize the variables

  var array = Array<AnyObject>()
  var dict = Dictionary<String, AnyObject>()
  var make = "chevy"
  var year = 2008
  var color = "red"

STEP 2 : Set the Dictionary(adding keys and Values)

  dict["trackMake"] = make
  dict["trackYear"] = year
  dict["trackColor"] = color
  println("the dict is-\(dict)")

STEP 3 : Append the Dictionary to Array

  array.append(dict)
  println("the array is-\(array)")

STEP 4 : Get Array values to variable(create the variable for getting value)

  let getMakeValue =  array[0]["trackMake"]
  let getYearValue = array[0]["trackYear"]
  let getColorValue = array[0]["trackColor"]

  println("the getMakeValue is - \(getMakeValue)")
  println("the getYearValue is - \(getYearValue)")
  println("the getColorVlaue is - \(getColorValue)")   

STEP 5: If you want to get values to string, do the following steps

 var stringMakeValue:String = getMakeValue as String
 var stringYearValue:String = ("\(getYearValue as Int)")
 var stringColorValue:String = getColorValue as String

 println("the stringMakeValue is - \(stringMakeValue)")
 println("the stringYearValue is - \(stringYearValue)")
 println("the stringColorValue is - \(stringColorValue)")

STEP 6 : Finally the total output values are

the dict is-[trackMake: chevy, trackColor: red, trackYear: 2008]

the array is-[{
trackColor = red;
trackMake = chevy;
trackYear = 2008;
}]

the getMakeValue is - Optional(chevy)
the getYearValue is - Optional(2008)
the getColorVlaue is - Optional(red)

the stringMakeValue is - chevy
the stringYearValue is - 2008
the stringColorValue is - red

Thank You

Comments

1

This sounds like you are wanting an array of objects that represent vehicles. You can either have an array of dictionaries or an array of vehicle objects.

Likely you will want to go with an object as Swift arrays and dictionaries must be typed. So your dictionary with string keys to values of differing types would end up having the type [String : Any] and you would be stuck casting back and forth. This would make your array of type [[String : Any ]].

Using an object you would just have an array of that type. Say your vehicle object's type is named Vehicle, that would make your array of type [Vehicle] and each array access would return an instance of that type.

Comments

0

If I want to try it with my own statement. Which also I want to extend my array with the data in my dictionary and print just the key from dictionary:

var myArray = ["Abdurrahman","Yomna"]

var myDic: [String: Any] = [
    "ahmed": 23,
    "amal": 33,
    "fahdad": 88]

for index in 1...3 {

    let dict: [String: Any] = [
        "key": "new value"
    ]

    // get existing items, or create new array if doesn't exist
    var existingItems = myDic[myArray] as? [[String: Any]] ?? [[String: Any]]()

    // append the item
    existingItems.append(myArray)

    // replace back into `data`
    myDic[myArray] = existingItems
}

3 Comments

Did you mean to submit this as a new question?
No I mean I tried to solve same question of my but it shows error
If you are having trouble, you should ask a new question with additional details on the error you encountered, not submit this as an answer to an existing question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.