Introduction to Swift: Arrays

An array stores multiple values of the same type in an ordered list. Different from Objective-C arrays in Swift can contain only one type at a time, which is less error.prone. In this tutorial we will show the most common functions applied on arrays. To follow this tutorial you will need Xcode 6 and start a playground file. Xcode 6 can be downloaded from Apple's developer portal. 

Update: In Xcode Beta 3 Swift introduced a new Array type signature syntax. This tutorial is updated to reflect this changes.

Empty Array

To create an empty array, the array must be initialized with the type of object that will be added later.  

var emptyStringArray:[String] = []
// or
var emptyIntegerArray:[Int] = []

Declare Arrays

The explicit or inferred syntax can be used to declare an array

var colorArray:Array<String> = ["Red","Blue","Green"]
var colorArray:[String] = ["Red","Blue","Green"]
var colorArray = ["Red","Blue","Green"]

Change Values

To change one or more values inside an array the index must be passed using object subscription

colorArray[0] = "Brown"
// colorArray = Brown, Blue, Green
colorArray[1...2] = ["Purple", "Pink"]
// colorArray = Brown, Purple, Pink

Remove items

The removeAtIndex function removes the items at the specific index. The removeLast function removes the last item in the array. Using the removeAll function all items are removed from the array.

// colorArray = Brown, Pink
// colorArray = Brown
// colorArray is empty

Add items

The append function can be used to append an item to the end of an existing array. Alternatively the + operand can be used.
To insert an item to a specifix index use the insert(atIndex) function

// colorArray = Yellow
colorArray += "Blue"
// colorArray = Yellow, Blue
// colorArray = Yellow, Red, Blue

Add an Array 

Am array can be added to an existing array using the + operand.

var anotherColorArray = ["Black, "White"]
colorArray += anotherColorArray
// colorArray = Yellow, Red, Blue, Black, White

Count the number of items

To count the number of items in an array the count function can be used.

let count = colorArray.count  
// count = 5

Reverse items 

To reverse the items in a array use the reverse function

// colorArray = White, Black, Blue, Red, Yellow

This finished this part of the introduction serie of Swift programming.