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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// 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? print(array.count) // remove the last item in the array array.removeLast() // remove an item at a particular index array.removeAtIndex(3) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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) data.append(formatter.stringFromNumber(number)!) } return data } |
For everything else about Swift Arrays, check out the Collection Types section of The Swift Programming Language: