Array
8 methodsAn 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
| Name | Type | Description |
|---|---|---|
| newElement | Element | Element to append. |
Returns
Void
Example
var nums = [1, 2]
nums.append(3)
// nums == [1, 2, 3]Array.count -> IntThe number of elements in the array.
Returns
Int
Example
let nums = [1, 2, 3]
print(nums.count) // 3Array.remove(at: Int) -> ElementRemoves and returns the element at the specified position, shifting subsequent elements.
Parameters
| Name | Type | Description |
|---|---|---|
| at | Int | Index of element to remove. |
Returns
Element
Example
var nums = [1, 2, 3]
let removed = nums.remove(at: 1)
// removed == 2, nums == [1, 3]Array.contains(_ element: Element) -> BoolReturns true if the array contains an element equal to the given value.
Parameters
| Name | Type | Description |
|---|---|---|
| element | Element | Element to search for. |
Returns
Bool
Example
let nums = [1, 2, 3]
print(nums.contains(2)) // true
print(nums.contains(9)) // falseArray.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
| Name | Type | Description |
|---|---|---|
| transform | (Element) -> T | Mapping closure. |
Returns
[T]
Example
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
| Name | Type | Description |
|---|---|---|
| isIncluded | (Element) -> Bool | Predicate closure. |
Returns
[Element]
Example
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
| Name | Type | Description |
|---|---|---|
| by | (Element, Element) -> Bool | Comparison closure (default ascending). |
Returns
[Element]
Example
let nums = [3, 1, 2]
let asc = nums.sorted() // [1, 2, 3]
let desc = nums.sorted(by: >) // [3, 2, 1]Array.joined(separator: String) -> StringReturns a string containing the elements of the sequence, separated by the given separator.
Parameters
| Name | Type | Description |
|---|---|---|
| separator | String | Separator between elements. |
Returns
String
Example
let parts = ["a", "b", "c"]
let s = parts.joined(separator: "-")
// s == "a-b-c"