Basic array properties and methods
An array is a Collection, which is itself a Sequence. If those terms have a familiar ring, they should: the same is true of a String’s characters, which I called a character sequence For this reason, an array and a character sequence bear some striking similarities to one another.
As a collection, an array’s count read-only property reports the number of elements it contains. If an array’s count is 0, its isEmpty property is true.
An array’s first and last read-only properties return its first and last elements, but they are wrapped in an Optional because the array might be empty and so these prop‐ erties would need to be nil. This is one of those rare situations in Swift where you can wind up with an Optional wrapping an Optional. For example, consider an array of Optionals wrapping Ints, and what happens when you get the last property of such an array.
An array’s largest accessible index is one less than its count. You may find yourself calculating index values with reference to the count; for example, to refer to the last two elements of arr, you can say:
let arr = [1,2,3]
let slice = arr[arr.count-2...arr.count-1] // [2,3]Swift doesn’t adopt the modern convention of letting you use negative numbers as a shorthand for that calculation. On the other hand, for the common case where you want the last n elements of an array, you can use the suffix(_:) method:
let arr = [1,2,3]
let slice = arr.suffix(2) // [2,3]
Both suffix(_:) and its companion prefix(_:) yield ArraySlices, and have the remarkable feature that there is no penalty for going out of range:
let arr = [1,2,3]
let slice = arr.suffix(10) // [1,2,3] (and no crash)Instead of describing the size of the suffix or prefix by its count, you can express the limit of the suffix or prefix by its index:
let arr = [1,2,3]
let slice = arr.suffix(from:1) // [2,3]
let slice2 = arr.prefix(upTo:1) // [1]
let slice3 = arr.prefix(through:1) // [1,2]