Skip to content

Swift Array API

Swift's Array<T> — an ordered, random-access collection of elements, backed by contiguous storage.

1 class · 8 methods

Array

8 methods

An ordered, random-access collection. Arrays are value types in Swift.

Array.append(_ newElement: Element)

Adds a new element at the end of the array.

Parameters

NameTypeDescription
newElementElementElement to append.

Returns

Void

Example

swift
var nums = [1, 2]
nums.append(3)
// nums == [1, 2, 3]
Array.count -> Int

The number of elements in the array.

Returns

Int

Example

swift
let nums = [1, 2, 3]
print(nums.count)  // 3
Array.remove(at: Int) -> Element

Removes and returns the element at the specified position, shifting subsequent elements.

Parameters

NameTypeDescription
atIntIndex of element to remove.

Returns

Element

Example

swift
var nums = [1, 2, 3]
let removed = nums.remove(at: 1)
// removed == 2, nums == [1, 3]
Array.contains(_ element: Element) -> Bool

Returns true if the array contains an element equal to the given value.

Parameters

NameTypeDescription
elementElementElement to search for.

Returns

Bool

Example

swift
let nums = [1, 2, 3]
print(nums.contains(2))  // true
print(nums.contains(9))  // false
Array.map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

Returns an array containing the results of mapping the given closure over the sequence's elements.

Parameters

NameTypeDescription
transform(Element) -> TMapping closure.

Returns

[T]

Example

swift
let nums = [1, 2, 3]
let squares = nums.map { $0 * $0 }
// squares == [1, 4, 9]
Array.filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

Returns an array containing the elements that satisfy the given predicate.

Parameters

NameTypeDescription
isIncluded(Element) -> BoolPredicate closure.

Returns

[Element]

Example

swift
let nums = [1, 2, 3, 4]
let evens = nums.filter { $0 % 2 == 0 }
// evens == [2, 4]
Array.sorted(by: (Element, Element) throws -> Bool) rethrows -> [Element]

Returns the elements of the sequence, sorted using the given comparison closure.

Parameters

NameTypeDescription
by(Element, Element) -> BoolComparison closure (default ascending).

Returns

[Element]

Example

swift
let nums = [3, 1, 2]
let asc = nums.sorted()                  // [1, 2, 3]
let desc = nums.sorted(by: >)            // [3, 2, 1]
Array.joined(separator: String) -> String

Returns a string containing the elements of the sequence, separated by the given separator.

Parameters

NameTypeDescription
separatorStringSeparator between elements.

Returns

String

Example

swift
let parts = ["a", "b", "c"]
let s = parts.joined(separator: "-")
// s == "a-b-c"