Array

struct Array<T>

Conceptually, Array is an efficient, tail-growable random-access collection of arbitrary elements.

Common Properties of Array Types

The information in this section applies to all three of Swift's array types, Array<T>, ContiguousArray<T>, and ArraySlice<T>. When you read the word "array" here in a normal typeface, it applies to all three of them.

Value Semantics

Each array variable, let binding, or stored property has an independent value that includes the values of all of its elements. Therefore, mutations to the array are not observable through its copies:

var a = [1, 2, 3]
var b = a
b[0] = 4
println("a=\(a), b=\(b)")     // a=[1, 2, 3], b=[4, 2, 3]

(Of course, if the array stores class references, the objects are shared; only the values of the references are independent)

Arrays use Copy-on-Write so that their storage and elements are only copied lazily, upon mutation, when more than one array instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost O(N) time and space, where N is the length of the array.

Growth and Capacity

When an array's contiguous storage fills up, new storage must be allocated and elements must be moved to the new storage. Array, ContiguousArray, and ArraySlice share an exponential growth strategy that makes append a constant time operation when amortized over many invocations. In addition to a count property, these array types have a capacity that reflects their potential to store elements without reallocation, and when you know how many elements you'll store, you can call reserveCapacity to pre-emptively reallocate and prevent intermediate reallocations.

Objective-C Bridge

The main distinction between Array and the other array types is that it interoperates seamlessly and efficiently with Objective-C.

Array<T> is considered bridged to Objective-C iff T is bridged to Objective-C.

When T is a class or @objc protocol type, Array may store its elements in an NSArray. Since any arbitrary subclass of NSArray can become an Array, there are no guarantees about representation or efficiency in this case (see also ContiguousArray). Since NSArray is immutable, it is just as though the storage was shared by some copy: the first in any sequence of mutating operations causes elements to be copied into unique, contiguous storage which may cost O(N) time and space, where N is the length of the array (or more, if the underlying NSArray is has unusual performance characteristics).

Bridging to Objective-C

Any bridged Array can be implicitly converted to an NSArray. When T is a class or @objc protocol, bridging takes O(1) time and O(1) space. Other Arrays must be bridged element-by-element, allocating a new object for each element, at a cost of at least O(count) time and space.

Bridging from Objective-C

An NSArray can be implicitly or explicitly converted to any bridged Array<T>. This conversion calls copyWithZone on the NSArray, to ensure it won't be modified, and stores the result in the Array. Type-checking, to ensure the NSArray's elements match or can be bridged to T, is deferred until the first element access.

Inheritance ArrayLiteralConvertible, CollectionType, DebugPrintable, ExtensibleCollectionType, MutableCollectionType, MutableSliceable, Printable, RangeReplaceableCollectionType, Reflectable, SequenceType, Sliceable, _ArrayType, _CollectionType, _DestructorSafeContainer, _ExtensibleCollectionType, _SequenceType, _Sequence_Type, _Sliceable, __ArrayType View Protocol Hierarchy →
Associated Types
Element = T

The type of element stored by this Array

SubSlice = ArraySlice<T>

A type that can represent a sub-range of an Array

Generator = IndexingGenerator<[T]>

Type alias inferred.

Index = Int

Type alias inferred.

SubSequence = ArraySlice<T>

Type alias inferred.

Import import Swift

Initializers

init()

Construct an empty Array

Declaration

init()
init(_: _ArrayBuffer<T>)

Initialization from an existing buffer does not have "array.init" semantics because the caller may retain an alias to buffer.

Declaration

init(_ buffer: _ArrayBuffer<T>)
init<S : SequenceType where T == T>(_: S)

Construct from an arbitrary sequence with elements of type T

Declaration

init<S : SequenceType where T == T>(_ s: S)
init(_fromCocoaArray:noCopy:)

Construct from the given _NSArrayCoreType.

If noCopy is true, either source must be known to be immutable, or the resulting Array must not survive across code that could mutate source.

Declaration

init(_fromCocoaArray source: _NSArrayCoreType, noCopy: Bool = default)
init(arrayLiteral:)

Create an instance containing elements.

Declaration

init(arrayLiteral elements: T...)
init(count:repeatedValue:)

Construct a Array of count elements, each initialized to repeatedValue.

Declaration

init(count: Int, repeatedValue: T)

Instance Variables

var capacity: Int

How many elements the Array can store without reallocation

Declaration

var capacity: Int { get }
var count: Int

How many elements the Array stores

Declaration

var count: Int { get }
var debugDescription: String

A textual representation of self, suitable for debugging.

Declaration

var debugDescription: String { get }
var description: String

A textual representation of self.

Declaration

var description: String { get }
var endIndex: Int

A "past-the-end" element index; the successor of the last valid subscript argument.

Declaration

var endIndex: Int { get }
var first: T?

The first element, or nil if the array is empty

Declaration

var first: T? { get }
var isEmpty: Bool

true if and only if the Array is empty

Declaration

var isEmpty: Bool { get }
var last: T?

The last element, or nil if the array is empty

Declaration

var last: T? { get }
var startIndex: Int

Always zero, which is the index of the first element when non-empty.

Declaration

var startIndex: Int { get }

Subscripts

subscript(_: Int)

Declaration

subscript(index: Int) -> T
subscript(_: Range<Int>)

Declaration

subscript(subRange: Range<Int>) -> ArraySlice<T>

Instance Methods

mutating func append(_:)

Append newElement to the Array

Complexity: amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

Declaration

mutating func append(newElement: T)
mutating func extend(_:)

Append the elements of newElements to self.

Complexity: O(length of result)

Declaration

mutating func extend<S : SequenceType where T == T>(newElements: S)
func filter(_:)

Return an Array containing the elements x of self for which includeElement(x) is true

Declaration

func filter(includeElement: (T) -> Bool) -> [T]
func flatMap(_:)

Return an Array containing the results of calling transform(x) on each element x of self and flattening the result.

Declaration

func flatMap<U>(transform: @noescape (T) -> [U]) -> [U]
func generate()

Return a generator over the elements.

Complexity: O(1)

Declaration

func generate() -> IndexingGenerator<[T]>
func getMirror()

Returns a mirror that reflects self.

Declaration

func getMirror() -> MirrorType
mutating func insert(_:atIndex:)

Insert newElement at index i.

Requires: i <= count

Complexity: O(count).

Declaration

mutating func insert(newElement: T, atIndex i: Int)
func join(_:)

Interpose self between each consecutive pair of elements, and concatenate the elements of the resulting sequence. For example, [-1, -2].join([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) yields [1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]

Declaration

func join<S : SequenceType where [T] == [T]>(elements: S) -> [T]
func map(_:)

Return an Array containing the results of calling transform(x) on each element x of self

Declaration

func map<U>(transform: (T) -> U) -> [U]
func reduce(_:combine:)

Return the result of repeatedly calling combine with an accumulated value initialized to initial and each element of self, in turn, i.e. return combine(combine(...combine(combine(initial, self[0]), self[1]),...self[count-2]), self[count-1]).

Declaration

func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U
mutating func removeAll(_:)

Remove all elements.

Postcondition: capacity == 0 iff keepCapacity is false.

Complexity: O(count(self)).

Declaration

mutating func removeAll(keepCapacity: Bool = default)
mutating func removeAtIndex(_:)

Remove and return the element at index i

Invalidates all indices with respect to self.

Complexity: O(count).

Declaration

mutating func removeAtIndex(index: Int) -> T
mutating func removeLast()

Remove an element from the end of the Array in O(1). Requires: count > 0

Declaration

mutating func removeLast() -> T
mutating func removeRange(_:)

Remove the indicated subRange of elements

Complexity: O(count).

Declaration

mutating func removeRange(subRange: Range<Int>)
mutating func replaceRange(_:with:)

Replace the given subRange of elements with newElements.

Complexity: O(count(subRange)) if subRange.endIndex == self.endIndex and isEmpty(newElements), O(N) otherwise.

Declaration

mutating func replaceRange<C : CollectionType where T == T>(subRange: Range<Int>, with newElements: C)
mutating func reserveCapacity(_:)

Reserve enough space to store minimumCapacity elements.

PostCondition: capacity >= minimumCapacity and the array has mutable contiguous storage.

Complexity: O(count)

Declaration

mutating func reserveCapacity(minimumCapacity: Int)
func reverse()

A Array containing the elements of self in reverse order

Declaration

func reverse() -> [T]
mutating func sort(_:)

Sort self in-place according to isOrderedBefore. Requires: isOrderedBefore induces a strict weak ordering over the elements.

Declaration

mutating func sort(isOrderedBefore: (T, T) -> Bool)
func sorted(_:)

Return a copy of self that has been sorted according to isOrderedBefore. Requires: isOrderedBefore induces a strict weak ordering over the elements.

Declaration

func sorted(isOrderedBefore: (T, T) -> Bool) -> [T]
mutating func splice(_:atIndex:)

Insert newElements at index i

Invalidates all indices with respect to self.

Complexity: O(count + count(newElements)).

Declaration

mutating func splice<S : CollectionType where T == T>(newElements: S, atIndex i: Int)
func withUnsafeBufferPointer(_:)

Call body(p), where p is a pointer to the Array's contiguous storage. If no such storage exists, it is first created.

Often, the optimizer can eliminate bounds checks within an array algorithm, but when that fails, invoking the same algorithm on body's argument lets you trade safety for speed.

Declaration

func withUnsafeBufferPointer<R>(body: @noescape (UnsafeBufferPointer<T>) -> R) -> R
mutating func withUnsafeMutableBufferPointer(_:)

Call body(p), where p is a pointer to the Array's mutable contiguous storage. If no such storage exists, it is first created.

Often, the optimizer can eliminate bounds- and uniqueness-checks within an array algorithm, but when that fails, invoking the same algorithm on body's argument lets you trade safety for speed.

Declaration

mutating func withUnsafeMutableBufferPointer<R>(body: @noescape (inout UnsafeMutableBufferPointer<T>) -> R) -> R