June 10th   2014

Array collection

  iOS , Swift

An array stores multiple values of the same type in an ordered fashion.

Back in Objective-C we had 3 types of collections:

  • NSArray - an ordered collection
  • NSDictionary - a key mapped collection
  • NSSet - a collection of unique objects

Swift provides only the first two collection types: arrays and dictionaries.

Array

An array stores multiple values of the same type in an ordered fashion. The major difference here is the requirement for the array elements to be of the same type. Here is an example:

let capitals = ["London", "Paris", "Madrid", "Berlin"]

Trying to add elements of different types will result in a compiler error:

let capitals = ["London", "Paris", "Madrid", "Berlin", 42]

Modifying arrays

Adding elements to the array is trivial. First, we'll redefine capitals as a variable and then add a new element at the end of it:

var capitals = ["London", "Paris", "Madrid", "Berlin"]
capitals += "Rome"

capitals now contains:

[0] "London"
[1] "Paris"
[2] "Madrid"
[3] "Berlin"
[4] "Rome"

Array type

As you probably noticed, we didn't have to specify the type of elements the array will store. This is because the compiler can infer the type from the value passed on the first assignment. However, there are instances when the initial value is either not known or not available. We'll therefore need to specify the array type:

var towns: String[]

towns is defined, it is not ready to use - one will get an error if trying to use it:

var towns: String[]
towns += "Manchester"
error: variable 'towns' used before being initialized

We'll need to assign a value to it before being able to use it:

var towns: String[]
towns = ["London"]
towns += "Manchester"

towns now contains:

[0] "London"
[1] "Manchester"

Useful array methods

var capitals = ["London", "Paris", "Madrid", "Berlin"]

capitals.isEmpty                  // false

capitals.count                    //  4
capitals.startIndex               //  0
capitals.endIndex                 //  4

capitals.reverse()                // ["Berlin", "Madrid", "Paris", "London"]

capitals.removeAtIndex(0)         //"London"           capitals is now: ["Paris", "Madrid", "Berlin"]
capitals.removeLast()             // "Berlin"           capitals is now: ["Paris", "Madrid"]

capitals.capacity                 // 4
// NB: The capitals array has only 2 elements. Capacity returns how many elements the array can store without reallocation.

capitals.append("Wien")                 // capitals is now: ["Paris", "Madrid", "Wien"]. Equivalent to +=
capitals.insert("London", atIndex: 1)   // capitals is now: ["Paris", "London", "Madrid", "Wien"]

Iterate through an array

var capitals = ["London", "Paris", "Madrid", "Berlin"]

for capital in capitals {
  println("name: \(capital)")
}

This will output:

name: London
name: Paris
name: Madrid
name: Berlin

«         »

Web Analytics