Arrays
Array[T] (or its shorthand [T]) holds an ordered, indexable, growable sequence of values of one type.
Creating
let xs: [Int] = [1, 2, 3];
let empty: [String] = [];
let zeroes: [Int] = Array(repeating: 0, count: 10);
The literal syntax [a, b, c] infers the element type from the contents; an empty literal needs the type written.
Indexing
var xs = [1, 2, 3];
let first = xs(0); // 1
xs(0) = 99; // requires xs to be `var`
The default subscript panics on out-of-bounds. For a non-panicking lookup, use the checked: variant which returns Optional[T]:
let xs = [1, 2, 3];
let i = 5;
if let .Some(v) = xs(checked: i) {
println("\(v)");
}
Other subscript variants cover common access patterns:
let xs = [1, 2, 3];
let i = 1;
xs(unchecked: i); // skips the bounds check (UB if out of range)
xs(0..<3); // ArraySlice[T]; panics if range is out of bounds
xs(checked: 0..<4); // Optional[ArraySlice[T]]
Common methods
var xs = [3, 1, 4, 1, 5];
xs.count; // number of elements
xs.isEmpty; // count == 0
xs.first(); // Optional[T]
xs.last(); // Optional[T]
xs.append(4); // mutates; xs must be `var`
xs.insert(0, at: 0);
xs.remove(at: 1); // returns the removed T
xs.pop(); // returns Optional[T]; removes the last
xs.popFirst(); // returns Optional[T]; removes the first
xs.contains(2); // Bool
xs.firstIndex(of: 2); // Optional[Int64]
xs.sort(); // requires T: Comparable, mutates
xs.sorted(); // non-mutating, returns a new Array
xs.reverse(); // mutates
xs.reversed(); // non-mutating, returns a reversed view
Iterator chain
Arrays have eager map and filter(where:) that return new arrays, and an iter() method that starts a lazy chain. See Iterators for the full set:
let xs = [1, 2, 3, 4, 5];
let doubled = xs.map { it * 2 }; // eager; returns a new Array
let evens = xs.filter(where: { it % 2 == 0 }); // eager; returns a new Array
let sum = xs.iter().fold(from: 0, by: { (acc, n) in acc + n });
let any = xs.iter().any(where: { it > 100 });
Adapters reached through iter() are lazy until a terminal operation forces them — those chains stay efficient even on long arrays. map and filter(where:) called directly on the array are eager and allocate their result up front.