How to use Arrays in Swift

Swift has its own built-in Array class. Although it’s bridged to NSArray, a Swift Array is something entirely different. Swift Arrays do not work with such trusted methods like addObject anymore.

Because I will probably have forgotten most of this by tomorrow, here’s a quick lowdown on how to play with Swift Arrays.

// create an empty array [type in square brackets]
var emptyArray = [String]()

// create an array with inferred values
var array = ["one", "two", "three"]

// loop through the array
for value in array {
    print("The value is \(value)")

// insert new value at a particular index
array.insert("two and a half", atIndex: 2)
var value = array[2]

// add something to the end of our array
array += ["new value"]
// or
array.append("another value")

// grab the last entry in our array
value = array.last!

// add another array
let anotherArray = ["four", "five", "six"]
array += anotherArray

// how many entries does our array have?

// remove the last item in the array

// remove an item at a particular index

Swift Arrays and Lazy Initialisation

Swift Arrays don’t like being initialised with a closure. God only knows why. We can however solve this puzzle with a simple function that returns our initialised values:

    lazy var data: [String] = self.initData()
    func initData() -> [String] {
        // initialize data array and return it
        var data = [String]()
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .SpellOutStyle
        for var i = 0; i < 30; i++ {
            let number = NSNumber.init(integer: i)
        return data

For everything else about Swift Arrays, check out the Collection Types section of The Swift Programming Language:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.