Array subscripting
The Array struct implements subscript methods to allow access to elements using square brackets after a reference to an array. You can use an Int inside the square brackets. For example, in an array consisting of three elements, if the array is referred to by a variable arr, then arr[1] accesses the second element.
You can also use a Range of Int inside the square brackets. For example, if arr is an array with three elements, then arr[1…2] signifies the second and third elements. Technically, an expression like arr[1…2] yields something called an ArraySlice. However, an ArraySlice is very similar to an array; for example, you can subscript an ArraySlice in just the same ways you would subscript an array, and an ArraySlice can be passed where an array is expected.
In general, therefore, you will probably pretend that an ArraySlice is an array. How‐ ever, they are not the same thing. An ArraySlice is not a new object; it’s a way of pointing into a section of the original array. For this reason, its index numbers are those of the original array. For example:
let arr = ["manny", "moe", "jack"]
let slice = arr[1...2]
print(slice[1]) // moe
The ArraySlice slice consists of "moe" and "jack" — and these are not merely "moe" and "jack" taken from the original array, but the "moe" and "jack" in the original array. For this reason, their index numbers are 1 and 2, just as in the original array. If you want to extract a new array based on this slice, coerce the slice to an Array:let arr2 = Array(slice)
print(arr2[1]) // jack
If the reference to an array is mutable (var, not let), then a subscript expression can be assigned to. This alters what’s in that slot. Of course, what is assigned must accord with the type of the array’s elements:var arr = [1,2,3]
arr[1] = 4 // arr is now [1,4,3]If the subscript is a range, what is assigned must be a slice. You can assign a literal array, because it will be cast for you to an ArraySlice; but if what you’re starting with is an array reference, you’ll have to cast it to a slice yourself. Such assignment can change the length of the array being assigned to:var arr = [1,2,3]
arr[1..<2] = [7,8] // arr is now [1,7,8,3]
arr[1..<2] = [] // arr is now [1,8,3]
arr[1..<1] = [10] // arr is now [1,10,8,3] (no element was removed!) let arr2 = [20,21]
// arr[1..<1] = arr2 // compile error! You have to say this:
arr[1..<1] = ArraySlice(arr2) // arr is now [1,20,21,10,8,3]It is a runtime error to access an element by a number larger than the largest element number or smaller than the smallest element number. If arr has three elements, speaking of arr[-1] or arr[3] is not illegal linguistically, but your program will crash.