How to add associative array elements in Swift

How do I create and add 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 have an array full of results where I can make a call like:

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

      

+3


source to share


4 answers


Just:

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

      

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

In such cases, make (extensive) use let

:



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

      

The above assumes yours myArray

was declared as

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

      

so the compiler knows that it will accept dictionary elements.

+5


source


I accept the answer above. It's good. Even if you gave the correct answer, I like the simplest way. The following steps are helpful if you guys are following this. Also if someone is new to the fast and if they get through it, they can easily understand the steps.

STEP 1: declare and initialize variables

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

      

STEP 2: Install the dictionary (add keys and values)

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

      

STEP 3: add dictionary to array

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

      



STEP 4: Get the values ​​of the variable array (create a variable to get the 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 the values ​​in the string, follow these 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, general output values

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

+3


source


It is like you want an array of objects to represent vehicles. You can have an array of dictionaries or an array of vehicle objects.

You will probably want to go with an object, as Swift arrays and dictionaries have to be printed. So your dictionary with string keys to values ​​of different types will be of type [String : Any]

and you will loop back and forth. This will make your array of type [[String : Any ]]

.

Using an object, you will only have an array of this type. Say your vehicle type has a name Vehicle

, which will make your array of type [Vehicle]

and every access to the array will return an instance of that type.

+1


source


If I want to try this with my own statement. Which also I want to expand my array with the data in my dictionary and only print the key from the 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
}

      

0


source







All Articles