Arrays inherit from a number of standard Swift protocols, some of which include ArrayLiteralConvertible, Mutable Sliceable, CustomStringConvertible, CollectionType, Mutable CollectionType, Indexable, RangeReplaceableCollectionType,
and SequenceType (see “Built-In Protocols” on page 175). This
provides them with many additional capabilities, some exam‐ ples of which are provided here.
Much of the inherited functionality you can apply to arrays uses closures. These are anonymous functions that perform some operation on one or two elements of the array (such as a transform, or comparison). See the section “Closures” on page 75 for more information.
The examples that follow are demonstrated using this array of strings:
var names = ["John", "Zoe", "Laura", "albert", "Allen"] arrayName.contains()
Returns a Bool value that indicates if a specific value is contained in the array.
names.contains("John") // returns true
names.contains("Lisa") // returns false arrayName.dropFirst([i])
Returns an array slice that contains all but the first i ele‐
ments of arrayName. If i is omitted, it defaults to 1.
See “Slices” on page 56.
names.dropFirst(2)
arrayName.dropLast([i])
Returns an array slice that contains all but the last i ele‐
ments of arrayName. If i is omitted, it defaults to 1.
See “Slices” on page 56.
names.dropLast(2)
// returns ["John", "Zoe", "Laura"] as a slice arrayName.elementsEqual()
Returns a Bool value that indicates if two arrays contain equal values in the same order.
let namesCopy = names
names.elementsEqual(namesCopy) // returns true
names.elementsEqual(namesCopy.sort()) // returns false arrayName.filter()
Returns a new array that contains only the elements that match some condition, which is defined by using a closure. This example filters names longer than four char‐ acters:
names.filter { $0.characters.count > 4 } // returns ["Laura", "albert", "Allen"] arrayName.flatMap()
Returns a new array that is dimensionally flatter than
arrayName, in which each element has been transformed
by a mapping function that is defined by using a closure. This example returns an array in which all strings from the original array of arrays have been converted to upper‐ case characters:
let arrOfArrays = [["Bill", "Fred"], ["Mary"]] let flatArray = arrOfArrays.flatMap() {$0.map{$0.uppercaseString}}
// flatArray holds ["BILL", "FRED", "MARY"] arrayName.forEach()
Calls the body of the closure on each element of the array, producing similar functionality to for i in arrayName { ... }.
names.forEach { print($0) }
arrayName.indexOf(someValue)
Returns an optional integer representing the position of
someValue in the array, or nil if the value is not present. names.indexOf("John") // returns 4?
arrayName.joinWithSeparator(someString)
For an array of strings, returns a new string comprising the elements of arrayName interposed with someString.
names.joinWithSeparator("; ")
// returns "John; Zoe; Laura; albert; Allen" arrayName.map()
Returns a new array in which each element has been transformed by a mapping function, which is defined by using a closure. This example returns an array in which any string from the original array that does not start with an uppercase “A” is prefixed with an asterisk (*):
names.map { $0.hasPrefix("A") ? $0 : "*" + $0 } // returns:
// ["*John", "*Zoe", "*Laura", "*albert", "Allen"] arrayName.prefix(i)
Returns an array slice that contains up to the first i ele‐
ments of arrayName. See also “Slices” on page 56.
names.prefix(2)
// returns ["John", "Zoe"] as a slice arrayName.reduce()
Returns a single value (of the type stored in the array) derived by recursively applying a reduction filter (defined by using a closure) to each element of the array and the output of the previous recursion. This example seeds the recursion with an empty string ($0) and concatenates each
element of the array ($1) to the output of the previous
recursion ($0):
names.reduce("") { $0 + $1 } // returns "JohnZoeLauraalbertAllen"
arrayName.reverse()
Returns a new item of type ReverseRandomAccessCollec tion<T> that contains the elements of arrayName in reverse
order. You can cast this back to an array with as Array: names.reverse() asArray
// returns ["Allen", "albert", "Laura", "Zoe", "John"] arrayName.sort()
Returns a new array that contains the elements of
arrayName in sorted order. Use with an optional closure to
define how two elements sort with respect to each other. For example:
names.sort() { $0<$1 }
// returns ["Allen", "John", "Laura", "Zoe", "albert"] arrayName.split(separator: [, maxSplit:][, allowEmpty
Slices:])
Returns an array of array slices formed from the elements of arrayName, split at each occurrence of separator. maxSplit is optional, and defaults to Int.max. It specifies
the maximum number of splits that will take place. Any remaining unsplit content will be included in the last slice.
allowEmptySlices is optional and defaults to false. If set
to true, an empty slice will be included in the returned array for each pair of consecutive elements that match
separator.
let intArray = [5, 2, 0, 4, 5, 6, 0, 9, 0] let aa7 = intArray.split(0, maxSplit: 1) // returns [[5, 2], [4, 5, 6, 0, 9, 0]] arrayName.startsWith(anotherArray)
Returns a Bool value that indicates if arrayName begins
with the same elements as anotherArray, in the same
order. For example:
names.startsWith(["John", "Zoe"]) // returns true
names.startsWith(["Allen"]) // returns false
arrayName.suffix(i)
Returns an array slice that contains up to the last i ele‐
ments of arrayName. See also the next section, “Slices” on page 56.
names.suffix(2)
// returns ["albert", "Allen"] as a slice
Slices
A slice is a view into a subset of the elements of another collec‐ tion (such as an array). Slices are space and time efficient—they do not initially copy the original collection’s elements, but refer to them in-situ. Copies will be made, however, of elements that are mutated.
You can create a slice from an array using a range operator, as in this example:
var names = ["John", "Zoe", "Laura", "albert", "Allen"] var someNames = names[1...3]
// someNames is ["Zoe", "Laura", "albert"]
The new slice someNames is of type ArraySlice<String> and has
the following characteristics:
• The startIndex property of the slice is 1, and the endIndex property is 4, since the slice is a view into the
elements of the original array, in their positions in that array.
• If the source array is mutable, its elements can be modi‐ fied and this will not affect the contents of the slice (this includes inserting and removing elements, not just mutating those from which the slice was initially con‐ structed).
• If the slice is mutable, its elements can be updated and this will not affect the contents of the source array (this includes inserting and removing elements).
• So long as both the source array and slice are not muta‐ ted, indices of the slice and the source array can be used interchangeably.
• A slice is a view onto the elements of another collection, and will keep references to those elements even after the original collection goes out of scope, prolonging their life.