UnsafeMutableRawBufferPointer

struct UnsafeMutableRawBufferPointer

A non-owning view over a region of memory as a Collection of bytes.

Each 8-bit byte in memory is viewed as a UInt8 value independent of the type of values held in that memory.

Reads and writes on memory via UnsafeRawBufferPointer are untyped operations. Accessing this Collection's bytes does not bind the underlying memory to UInt8. The underlying memory must be bound to some trivial type whenever it is accessed via a typed operation.

Note: A trivial type can be copied with just a bit-for-bit copy without any indirection or reference-counting operations. Generally, native Swift types that do not contain strong or weak references or other forms of indirection are trivial, as are imported C structs and enums. Copying memory that contains values of nontrivial type can only be done safely with a typed pointer. Copying bytes directly from nontrivial in-memory values does not produce valid copies and can only be done by calling a C API such as memmove.

In addition to the Collection interface, the following subset of UnsafeMutableRawPointer's interface to raw memory is provided with debug mode bounds checks: load(fromByteOffset:**as:), storeBytes(of:**toByteOffset:as:) **copyBytes(from:**count:)

This is only a view into memory and does not own the memory. Copying a value of type UnsafeMutableBytes does not copy the underlying memory. However, initializing another collection, such as [UInt8], with an UnsafeMutableBytes into copies bytes out of memory.

Example: `swift // View a slice of memory at someBytes. Nothing is copied. var destBytes = someBytes[0..<n]

// Copy the slice of memory into a buffer of UInt8. var byteArray = UInt8

// Copy another slice of memory into the buffer. byteArray += someBytes[n..<m] `

Assigning into a range of subscripts copies bytes into the memory.

Example (continued): swift // Copy a another slice of memory back into the original slice. destBytes[0..<n] = someBytes[m..<(m+n)]

TODO: Specialize index and formIndex and _failEarlyRangeCheck as in UnsafeBufferPointer.

Inheritance BidirectionalCollection, BidirectionalIndexable, Collection, CustomDebugStringConvertible, Indexable, IndexableBase, MutableCollection, MutableIndexable, RandomAccessCollection, RandomAccessIndexable, Sequence View Protocol Hierarchy →
Associated Types
Index = Int

A type that represents a position in the collection.

Valid indices consist of the position of every element and a "past the end" position that's not valid for use as a subscript argument.

See Also: endIndex

IndexDistance = Int

A type used to represent the number of steps between two indices, where one value is reachable from the other.

In Swift, reachability refers to the ability to produce one value from the other through zero or more applications of index(after:).

SubSequence = UnsafeMutableRawBufferPointer

A sequence that can represent a contiguous subrange of the collection's elements.

Indices = CountableRange<Int>

A type that can represent the indices that are valid for subscripting the collection, in ascending order.

Iterator = UnsafeMutableRawBufferPointer.Iterator

Type alias inferred.

Element = UInt8

Type alias inferred.

Index = Int

Type alias inferred.

Nested Types UnsafeMutableRawBufferPointer.Iterator
Import import Swift

Initializers

init(_: UnsafeMutableRawBufferPointer)

Converts UnsafeMutableRawBufferPointer to UnsafeRawBufferPointer.

Declaration

init(_ bytes: UnsafeMutableRawBufferPointer)
init<T>(_: UnsafeMutableBufferPointer<T>)

Creates an UnsafeMutableRawBufferPointer over the contiguous bytes in buffer.

Precondition: T is a trivial type.

Declaration

init<T>(_ buffer: UnsafeMutableBufferPointer<T>)
init(mutating:)

Converts UnsafeRawBufferPointer to UnsafeMutableRawBufferPointer.

Declaration

init(mutating bytes: UnsafeRawBufferPointer)
init(start:count:)

Creates an UnsafeMutableRawBufferPointer over count contiguous bytes beginning at start.

If start is nil, count must be 0. However, count may be 0 even for a nonzero start.

Declaration

init(start: UnsafeMutableRawPointer?, count: Int)

Instance Variables

var baseAddress: UnsafeMutableRawPointer?

A pointer to the first byte of the buffer.

Declaration

var baseAddress: UnsafeMutableRawPointer? { get }
var count: Int

The number of bytes in the buffer.

Declaration

var count: Int { get }
var debugDescription: String

A textual representation of self, suitable for debugging.

Declaration

var debugDescription: String { get }
var endIndex: Int

The "past the end" position---that is, the position one greater than the last valid subscript argument.

The endIndex property of an UnsafeMutableRawBufferPointer instance is always identical to count.

Declaration

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

The first element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let firstNumber = numbers.first {
    print(firstNumber)
}
// Prints "10"

Declaration

var first: UInt8? { get }

Declared In

MutableCollection , RandomAccessCollection , Collection , BidirectionalCollection
var indices: UnsafeMutableRawBufferPointer.Indices

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: UnsafeMutableRawBufferPointer.Indices { get }
var isEmpty: Bool

A Boolean value indicating whether the collection is empty.

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

let horseName = "Silver"
if horseName.characters.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}
// Prints "Hi ho, Silver!")

Complexity: O(1)

Declaration

var isEmpty: Bool { get }

Declared In

MutableCollection , RandomAccessCollection , Collection , BidirectionalCollection
var last: UInt8?

The last element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let lastNumber = numbers.last {
    print(lastNumber)
}
// Prints "50"

Declaration

var last: UInt8? { get }

Declared In

RandomAccessCollection , BidirectionalCollection
var lazy: LazyCollection<UnsafeMutableRawBufferPointer>

A view onto this collection that provides lazy implementations of normally eager operations, such as map and filter.

Use the lazy property when chaining operations to prevent intermediate operations from allocating storage, or when you only need a part of the final collection to avoid unnecessary computation.

See Also: LazySequenceProtocol, LazyCollectionProtocol.

Declaration

var lazy: LazyCollection<UnsafeMutableRawBufferPointer> { get }

Declared In

MutableCollection , Collection
var startIndex: Int

Always zero, which is the index of the first byte in a non-empty buffer.

Declaration

var startIndex: Int { get }
var underestimatedCount: Int

A value less than or equal to the number of elements in the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var underestimatedCount: Int { get }

Declared In

MutableCollection , RandomAccessCollection , Collection , BidirectionalCollection , Sequence

Subscripts

subscript(_: ClosedRange<Int>)

Accesses a contiguous subrange of the collection's elements.

The accessed slice uses the same indices for the same elements as the original collection. Always use the slice's startIndex property instead of assuming that its indices start at a particular value.

This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print(streetsSlice)
// Prints "["Channing", "Douglas", "Evarts"]"

let index = streetsSlice.index(of: "Evarts")    // 4
streets[index!] = "Eustace"
print(streets[index!])
// Prints "Eustace"

bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Declaration

subscript(bounds: ClosedRange<Int>) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
subscript(_: Int)

Accesses the ith byte in the memory region as a UInt8 value.

Declaration

subscript(i: Int) -> UInt8 { get nonmutating set }
subscript(_: Range<Int>)

Accesses the bytes in the memory region within bounds as a UInt8 values.

Declaration

subscript(bounds: Range<Int>) -> UnsafeMutableRawBufferPointer { get nonmutating set }

Declared In

UnsafeMutableRawBufferPointer, MutableCollection

Static Methods

static func allocate(count:)

Allocate memory for size bytes with word alignment.

Postcondition: The memory is allocated, but not initialized.

Declaration

static func allocate(count size: Int) -> UnsafeMutableRawBufferPointer

Instance Methods

func contains(_:)

Returns a Boolean value indicating whether the sequence contains the given element.

This example checks to see whether a favorite actor is in an array storing a movie's cast.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
print(cast.contains("Marlon"))
// Prints "true"
print(cast.contains("James"))
// Prints "false"

element: The element to find in the sequence. Returns: true if the element was found in the sequence; otherwise, false.

Declaration

func contains(_ element: UInt8) -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func contains(where:)

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

You can use the predicate to check for an element of a type that doesn't conform to the Equatable protocol, such as the HTTPResponse enumeration in this example.

enum HTTPResponse {
    case ok
    case error(Int)
}

let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
    if case .error = element {
        return true
    } else {
        return false
    }
}
// 'hadError' == true

Alternatively, a predicate can be satisfied by a range of Equatable elements or a general condition. This example shows how you can check an array for an expense greater than $100.

let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 }
// 'hasBigPurchase' == true

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: true if the sequence contains an element that satisfies predicate; otherwise, false.

Declaration

func contains(where predicate: (UInt8) throws -> Bool) rethrows -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func copyBytes(from: UnsafeRawBufferPointer)

Copies count bytes from source into memory at self.

Precondition: count is non-negative.

Precondition: The memory at source..<source + count is initialized to some trivial type T.

Precondition: If the memory at self..<self+count is bound to a type U, then U is a trivial type, the underlying pointers source and self are properly aligned for type U, and count is a multiple of MemoryLayout<U>.stride.

Postcondition: The memory at self..<self+count is initialized to raw bytes. If the memory is bound to type U, then it contains values of type U.

Declaration

func copyBytes(from source: UnsafeRawBufferPointer)
func copyBytes<C : Collection where C.Iterator.Element == UInt8>(from: C)

Copies from a collection of UInt8 into memory at self.

Precondition: source.count <= self.count.

Precondition: If the memory at self..<self+count is bound to a type U, then U is a trivial type, the underlying pointer at self is properly aligned for type U, and source.count is a multiple of MemoryLayout<U>.stride.

Postcondition: The memory at self..<self+count is initialized to raw bytes. If the memory is bound to type U, then it contains values of type U.

Declaration

func copyBytes<C : Collection where C.Iterator.Element == UInt8>(from source: C)
func deallocate()

Deallocate this memory allocated for bytes number of bytes.

Precondition: The memory is not initialized.

Postcondition: The memory has been deallocated.

Declaration

func deallocate()
func distance(from:to:)

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

Parameters: start: A valid index of the collection. end: Another valid index of the collection. If end is equal to start, the result is zero. Returns: The distance between start and end. The result can be negative only if the collection conforms to the BidirectionalCollection protocol.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the resulting distance.

Declaration

func distance(from start: Int, to end: Int) -> IntDistance

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
func dropFirst()

Returns a subsequence containing all but the first element of the sequence.

The following example drops the first element from an array of integers.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst())
// Prints "[2, 3, 4, 5]"

If the sequence has no elements, the result is an empty subsequence.

let empty: [Int] = []
print(empty.dropFirst())
// Prints "[]"

Returns: A subsequence starting after the first element of the sequence.

Complexity: O(1)

Declaration

func dropFirst() -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func dropFirst(_:)

Returns a subsequence containing all but the given number of initial elements.

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"

n: The number of elements to drop from the beginning of the collection. n must be greater than or equal to zero. Returns: A subsequence starting after the specified number of elements.

Complexity: O(n), where n is the number of elements to drop from the beginning of the collection.

Declaration

func dropFirst(_ n: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func dropLast()

Returns a subsequence containing all but the last element of the sequence.

The sequence must be finite. If the sequence has no elements, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast())
// Prints "[1, 2, 3, 4]"

If the sequence has no elements, the result is an empty subsequence.

let empty: [Int] = []
print(empty.dropLast())
// Prints "[]"

Returns: A subsequence leaving off the last element of the sequence.

Complexity: O(n), where n is the length of the sequence.

Declaration

func dropLast() -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func dropLast(_:)

Returns a subsequence containing all but the specified number of final elements.

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"

n: The number of elements to drop off the end of the collection. n must be greater than or equal to zero. Returns: A subsequence that leaves off the specified number of elements at the end.

Complexity: O(n), where n is the length of the collection.

Declaration

func dropLast(_ n: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func elementsEqual(_:)

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

At least one of the sequences must be finite.

This example tests whether one countable range shares the same elements as another countable range and an array.

let a = 1...3
let b = 1...10

print(a.elementsEqual(b))
// Prints "false"
print(a.elementsEqual([1, 2, 3]))
// Prints "true"

other: A sequence to compare to this sequence. Returns: true if this sequence and other contain the same elements in the same order.

See Also: elementsEqual(_:by:)

Declaration

func elementsEqual<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence) -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func elementsEqual(_:by:)

Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements, using the given predicate as the equivalence test.

At least one of the sequences must be finite.

The predicate must be a equivalence relation over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areEquivalent(a, a) is always true. (Reflexivity)
  • areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry)
  • If areEquivalent(a, b) and areEquivalent(b, c) are both true, then areEquivalent(a, c) is also true. (Transitivity)

Parameters: other: A sequence to compare to this sequence. areEquivalent: A predicate that returns true if its two arguments are equivalent; otherwise, false. Returns: true if this sequence and other contain equivalent items, using areEquivalent as the equivalence test; otherwise, false.

See Also: elementsEqual(_:)

Declaration

func elementsEqual<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence, by areEquivalent: (UInt8, UInt8) throws -> Bool) rethrows -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func enumerated()

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.

This example enumerates the characters of the string "Swift" and prints each character along with its place in the string.

for (n, c) in "Swift".characters.enumerated() {
    print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"

When enumerating a collection, the integer part of each pair is a counter for the enumeration, not necessarily the index of the paired value. These counters can only be used as indices in instances of zero-based, integer-indexed collections, such as Array and ContiguousArray. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the zip(_:_:) function.

This example iterates over the indices and elements of a set, building a list of indices of names with five or fewer letters.

let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [SetIndex<String>] = []
for (i, name) in zip(names.indices, names) {
    if name.characters.count <= 5 {
        shorterIndices.append(i)
    }
}

Now that the shorterIndices array holds the indices of the shorter names in the names set, you can use those indices to access elements in the set.

for i in shorterIndices {
    print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"

Returns: A sequence of pairs enumerating the sequence.

Declaration

func enumerated() -> EnumeratedSequence<UnsafeMutableRawBufferPointer>

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func filter(_:)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

In this example, filter is used to include only names shorter than five characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.characters.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

shouldInclude: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. Returns: An array of the elements that includeElement allowed.

Declaration

func filter(_ isIncluded: (UInt8) throws -> Bool) rethrows -> [UInt8]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func first(where:)

Returns the first element of the sequence that satisfies the given predicate or nil if no such element is found.

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. Returns: The first match or nil if there was no match.

Declaration

func first(where predicate: (UInt8) throws -> Bool) rethrows -> UInt8?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func flatMap<ElementOfResult>(_: (UInt8) throws -> ElementOfResult?)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

Use this method to receive an array of nonoptional values when your transformation produces an optional value.

In this example, note the difference in the result of using map and flatMap with a transformation that returns an optional Int value.

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = numbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let flatMapped: [Int] = numbers.flatMap { str in Int(str) }
// [1, 2, 5]

transform: A closure that accepts an element of this sequence as its argument and returns an optional value. Returns: An array of the non-nil results of calling transform with each element of the sequence.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

Declaration

func flatMap<ElementOfResult>(_ transform: (UInt8) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func flatMap<SegmentOfResult : Sequence>(_: (UInt8) throws -> SegmentOfResult)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

Use this method to receive a single-level collection when your transformation produces a sequence or collection for each element.

In this example, note the difference in the result of using map and flatMap with a transformation that returns an array.

let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(count: $0, repeatedValue: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(count: $0, repeatedValue: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()).

transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection. Returns: The resulting flattened array.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result. See Also: joined(), map(_:)

Declaration

func flatMap<SegmentOfResult : Sequence>(_ transform: (UInt8) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func forEach(_:)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

The two loops in the following example produce the same output:

let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"

numberWords.forEach { word in
    print(word)
}
// Same as above

Using the forEach method is distinct from a for-in loop in two important ways:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
  2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won't skip subsequent calls.

body: A closure that takes an element of the sequence as a parameter.

Declaration

func forEach(_ body: (UInt8) throws -> Swift.Void) rethrows

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func formIndex(_:offsetBy:)

Offsets the given index by the specified distance.

The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection.

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol.

See Also: index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func formIndex(_ i: inout Int, offsetBy n: IntDistance)

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
func formIndex(_:offsetBy:limitedBy:)

Offsets the given index by the specified distance, or so that it equals the given limiting index.

The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection, unless the index passed as limit prevents offsetting beyond those bounds.

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. Returns: true if i has been offset by exactly n steps without going beyond limit; otherwise, false. When the return value is false, the value of i is equal to limit.

See Also: index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func formIndex(_ i: inout Int, offsetBy n: IntDistance, limitedBy limit: Int) -> Bool

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
func formIndex(after:)

Replaces the given index with its successor.

i: A valid index of the collection. i must be less than endIndex.

Declaration

func formIndex(after i: inout Int)

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
func formIndex(before:)

Replaces the given index with its predecessor.

i: A valid index of the collection. i must be greater than startIndex.

Declaration

func formIndex(before i: inout Int)

Declared In

RandomAccessCollection, RandomAccessIndexable, BidirectionalCollection, BidirectionalIndexable
func index(_:offsetBy:)

Returns an index that is the specified distance from the given index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection.

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. Returns: An index offset by n from the index i. If n is positive, this is the same value as the result of n calls to index(after:). If n is negative, this is the same value as the result of -n calls to index(before:).

See Also: index(_:offsetBy:limitedBy:), formIndex(_:offsetBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Int, offsetBy n: IntDistance) -> Int

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
func index(_:offsetBy:limitedBy:)

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection, unless the index passed as limit prevents offsetting beyond those bounds.

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. limit: A valid index of the collection to use as a limit. If n > 0, a limit that is less than i has no effect. Likewise, if n < 0, a limit that is greater than i has no effect. Returns: An index offset by n from the index i, unless that index would be beyond limit in the direction of movement. In that case, the method returns nil.

See Also: index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Int, offsetBy n: IntDistance, limitedBy limit: Int) -> Int?

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
func index(of:)

Returns the first index where the specified value appears in the collection.

After using index(of:) to find the position of a particular element in a collection, you can use it to access the element by subscripting. This example shows how you can modify one of the names in an array of students.

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.index(of: "Maxime") {
    students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"

element: An element to search for in the collection. Returns: The first index where element is found. If element is not found in the collection, returns nil.

See Also: index(where:)

Declaration

func index(of element: UInt8) -> Int?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
func index(where:)

Returns the first index in which an element of the collection satisfies the given predicate.

You can use the predicate to find an element of a type that doesn't conform to the Equatable protocol or to find an element that matches particular criteria. Here's an example that finds a student name that begins with the letter "A":

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.index(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"

predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil.

See Also: index(of:)

Declaration

func index(where predicate: (UInt8) throws -> Bool) rethrows -> Int?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
func lexicographicallyPrecedes(_:)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.

This example uses the lexicographicallyPrecedes method to test which array of integers comes first in a lexicographical ordering.

let a = [1, 2, 2, 2]
let b = [1, 2, 3, 4]

print(a.lexicographicallyPrecedes(b))
// Prints "true"
print(b.lexicographicallyPrecedes(b))
// Prints "false"

other: A sequence to compare to this sequence. Returns: true if this sequence precedes other in a dictionary ordering; otherwise, false.

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use String APIs that perform localized comparison. See Also: lexicographicallyPrecedes(_:by:)

Declaration

func lexicographicallyPrecedes<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence) -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func lexicographicallyPrecedes(_:by:)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

Parameters: other: A sequence to compare to this sequence. areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: true if this sequence precedes other in a dictionary ordering as ordered by areInIncreasingOrder; otherwise, false.

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use String APIs that perform localized comparison instead. See Also: lexicographicallyPrecedes(_:)

Declaration

func lexicographicallyPrecedes<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence, by areInIncreasingOrder: (UInt8, UInt8) throws -> Bool) rethrows -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func load(fromByteOffset:as:)

Reads raw bytes from memory at self + offset and constructs a value of type T.

Precondition: offset + MemoryLayout<T>.size < self.count

Precondition: The underlying pointer plus offset is properly aligned for accessing T.

Precondition: The memory is initialized to a value of some type U such that T is layout compatible with U.

Declaration

func load<T>(fromByteOffset offset: Int = default, as type: T.Type) -> T
func makeIterator()

Returns an iterator over the bytes of this sequence.

Complexity: O(1).

Declaration

func makeIterator() -> UnsafeMutableRawBufferPointer.Iterator
func map(_:)

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

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercaseString }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.characters.count }
// 'letterCounts' == [6, 6, 3, 4]

transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type. Returns: An array containing the transformed elements of this sequence.

Declaration

func map<T>(_ transform: (UInt8) throws -> T) rethrows -> [T]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
@warn_unqualified_access func max()

Returns the maximum element in the sequence.

This example finds the smallest value in an array of height measurements.

let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let greatestHeight = heights.max()
print(greatestHeight)
// Prints "Optional(67.5)"

Returns: The sequence's maximum element. If the sequence has no elements, returns nil.

See Also: max(by:)

Declaration

@warn_unqualified_access func max() -> UInt8?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
@warn_unqualified_access func max(by:)

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

This example shows how to use the max(by:) method on a dictionary to find the key-value pair with the highest value.

let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
// Prints "Optional(("Heliotrope", 296))"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: The sequence's maximum element if the sequence is not empty; otherwise, nil.

See Also: max()

Declaration

@warn_unqualified_access func max(by areInIncreasingOrder: (UInt8, UInt8) throws -> Bool) rethrows -> UInt8?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
@warn_unqualified_access func min()

Returns the minimum element in the sequence.

This example finds the smallest value in an array of height measurements.

let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let lowestHeight = heights.min()
print(lowestHeight)
// Prints "Optional(58.5)"

Returns: The sequence's minimum element. If the sequence has no elements, returns nil.

See Also: min(by:)

Declaration

@warn_unqualified_access func min() -> UInt8?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
@warn_unqualified_access func min(by:)

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

This example shows how to use the min(by:) method on a dictionary to find the key-value pair with the lowest value.

let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let leastHue = hues.min { a, b in a.value < b.value }
print(leastHue)
// Prints "Optional(("Coral", 16))"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: The sequence's minimum element, according to areInIncreasingOrder. If the sequence has no elements, returns nil.

See Also: min()

Declaration

@warn_unqualified_access func min(by areInIncreasingOrder: (UInt8, UInt8) throws -> Bool) rethrows -> UInt8?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
mutating func partition(by:)

Reorders the elements of the collection such that all the elements that match the given predicate are after all the elements that do not match the predicate.

After partitioning a collection, there is a pivot index p where no element before p satisfies the belongsInSecondPartition predicate and every element at or after p satisfies belongsInSecondPartition.

In the following example, an array of numbers is partitioned by a predicate that matches elements greater than 30.

var numbers = [30, 40, 20, 30, 30, 60, 10]
let p = numbers.partition(by: { $0 > 30 })
// p == 5
// numbers == [30, 10, 20, 30, 30, 60, 40]

The numbers array is now arranged in two partitions. The first partition, numbers.prefix(upTo: p), is made up of the elements that are not greater than 30. The second partition, numbers.suffix(from: p), is made up of the elements that are greater than 30.

let first = numbers.prefix(upTo: p)
// first == [30, 10, 20, 30, 30]
let second = numbers.suffix(from: p)
// second == [60, 40]

belongsInSecondPartition: A predicate used to partition the collection. All elements satisfying this predicate are ordered after all elements not satisfying it. Returns: The index of the first element in the reordered collection that matches belongsInSecondPartition. If no elements in the collection match belongsInSecondPartition, the returned index is equal to the collection's endIndex.

Complexity: O(n)

Declaration

mutating func partition(by belongsInSecondPartition: (UInt8) throws -> Bool) rethrows -> Int

Declared In

MutableCollection
mutating func popFirst()

Removes and returns the first element of the collection.

Returns: The first element of the collection if the collection is not empty; otherwise, nil.

Complexity: O(1)

Declaration

mutating func popFirst() -> UInt8?

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
mutating func popLast()

Removes and returns the last element of the collection.

Returns: The last element of the collection if the collection has one or more elements; otherwise, nil.

Complexity: O(1). See Also: removeLast()

Declaration

mutating func popLast() -> UInt8?

Declared In

RandomAccessCollection, BidirectionalCollection
func prefix(_:)

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero. Returns: A subsequence starting at the beginning of this collection with at most maxLength elements.

Declaration

func prefix(_ maxLength: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func prefix(through:)

Returns a subsequence from the start of the collection through the specified position.

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.index(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

end: The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property. Returns: A subsequence up to, and including, the end position.

Complexity: O(1) See Also: prefix(upTo:)

Declaration

func prefix(through position: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
func prefix(upTo:)

Returns a subsequence from the start of the collection up to, but not including, the specified position.

The resulting subsequence does not include the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, but not including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.index(of: 40) {
    print(numbers.prefix(upTo: i))
}
// Prints "[10, 20, 30]"

Passing the collection's starting index as the end parameter results in an empty subsequence.

print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection. Returns: A subsequence up to, but not including, the end position.

Complexity: O(1) See Also: prefix(through:)

Declaration

func prefix(upTo end: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
func reduce(_:_:)

Returns the result of calling the given combining closure with each element of this sequence and an accumulating value.

The nextPartialResult closure is called sequentially with an accumulating value initialized to initialResult and each element of the sequence. This example shows how to find the sum of an array of numbers.

let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10

When numbers.reduce(_:_:) is called, the following steps occur:

  1. The nextPartialResult closure is called with the initial result and the first element of numbers, returning the sum: 1.
  2. The closure is called again repeatedly with the previous call's return value and each element of the sequence.
  3. When the sequence is exhausted, the last value returned from the closure is returned to the caller.

Parameters: initialResult: the initial accumulating value. nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller. Returns: The final accumulated value.

Declaration

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, UInt8) throws -> Result) rethrows -> Result

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
mutating func removeFirst()

Removes and returns the first element of the collection.

The collection must not be empty.

Returns: The first element of the collection.

Complexity: O(1) See Also: popFirst()

Declaration

mutating func removeFirst() -> UInt8

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
mutating func removeFirst(_:)

Removes the specified number of elements from the beginning of the collection.

n: The number of elements to remove. n must be greater than or equal to zero, and must be less than or equal to the number of elements in the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n).

Declaration

mutating func removeFirst(_ n: Int)

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection
mutating func removeLast()

Removes and returns the last element of the collection.

The collection must not be empty.

Returns: The last element of the collection.

Complexity: O(1) See Also: popLast()

Declaration

mutating func removeLast() -> UInt8

Declared In

RandomAccessCollection, BidirectionalCollection
mutating func removeLast(_:)

Removes the given number of elements from the end of the collection.

n: The number of elements to remove. n must be greater than or equal to zero, and must be less than or equal to the number of elements in the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

mutating func removeLast(_ n: Int)

Declared In

RandomAccessCollection, BidirectionalCollection
mutating func reverse()

Reverses the elements of the collection in place.

The following example reverses the elements of an array of characters:

var characters: [Character] = ["C", "a", "f", "é"]
characters.reverse()
print(cafe.characters)
// Prints "["é", "f", "a", "C"]

Complexity: O(n), where n is the number of elements in the collection.

Declaration

mutating func reverse()

Declared In

MutableCollection
func reversed()

Returns an array containing the elements of this sequence in reverse order.

The sequence must be finite.

Complexity: O(n), where n is the length of the sequence.

Returns: An array containing the elements of this sequence in reverse order.

Declaration

func reversed() -> [UInt8]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
mutating func sort()

Sorts the collection in place.

You can sort any mutable collection of elements that conform to the Comparable protocol by calling this method. Elements are sorted in ascending order.

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements that compare equal.

Here's an example of sorting a list of students' names. Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator (<).

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

To sort the elements of your collection in descending order, pass the greater-than operator (>) to the sort(by:) method.

students.sort(by: >)
print(students)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Declaration

mutating func sort()

Declared In

MutableCollection
mutating func sort(by:)

Sorts the collection in place, using the given predicate as the comparison between elements.

When you want to sort a collection of elements that doesn't conform to the Comparable protocol, pass a closure to this method that returns true when the first element passed should be ordered before the second.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements for which areInIncreasingOrder does not establish an order.

In the following example, the closure provides an ordering for an array of a custom enumeration that describes an HTTP response. The predicate orders errors before successes and sorts the error responses by their error code.

enum HTTPResponse {
    case ok
    case error(Int)
}

var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
responses.sort {
    switch ($0, $1) {
    // Order errors by code
    case let (.error(aCode), .error(bCode)):
        return aCode < bCode

    // All successes are equivalent, so none is before any other
    case (.ok, .ok): return false

    // Order errors before successes
    case (.error, .ok): return true
    case (.ok, .error): return false
    }
}
print(responses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"

Alternatively, use this method to sort a collection of elements that do conform to Comparable when you want the sort to be descending instead of ascending. Pass the greater-than operator (>) operator as the predicate.

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort(by: >)
print(students)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

Declaration

mutating func sort(by areInIncreasingOrder: (UInt8, UInt8) -> Bool)

Declared In

MutableCollection
func sorted()

Returns the elements of the collection, sorted.

You can sort any collection of elements that conform to the Comparable protocol by calling this method. Elements are sorted in ascending order.

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements that compare equal.

Here's an example of sorting a list of students' names. Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator (<).

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

To sort the elements of your collection in descending order, pass the greater-than operator (>) to the sorted(by:) method.

let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Returns: A sorted array of the collection's elements.

See Also: sorted(by:) MutatingVariant: sort

Declaration

func sorted() -> [UInt8]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func sorted(by:)

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

When you want to sort a collection of elements that don't conform to the Comparable protocol, pass a predicate to this method that returns true when the first element passed should be ordered before the second. The elements of the resulting array are ordered according to the given predicate.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements for which areInIncreasingOrder does not establish an order.

In the following example, the predicate provides an ordering for an array of a custom HTTPResponse type. The predicate orders errors before successes and sorts the error responses by their error code.

enum HTTPResponse {
    case ok
    case error(Int)
}

let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
let sortedResponses = responses.sorted {
    switch ($0, $1) {
    // Order errors by code
    case let (.error(aCode), .error(bCode)):
        return aCode < bCode

    // All successes are equivalent, so none is before any other
    case (.ok, .ok): return false

    // Order errors before successes
    case (.error, .ok): return true
    case (.ok, .error): return false
    }
}
print(sortedResponses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"

You also use this method to sort elements that conform to the Comparable protocol in descending order. To sort your collection in descending order, pass the greater-than operator (>) as the areInIncreasingOrder parameter.

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Calling the related sorted() method is equivalent to calling this method and passing the less-than operator (<) as the predicate.

print(students.sorted())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
print(students.sorted(by: <))
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: A sorted array of the collection's elements.

See Also: sorted() MutatingVariant: sort

Declaration

func sorted(by areInIncreasingOrder: (UInt8, UInt8) -> Bool) -> [UInt8]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func split(_:maxSplits:omittingEmptySubsequences:)

Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the collection are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string at each space character (" "). The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.characters.split(separator: " ")
                     .map(String.init))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(line.characters.split(separator: " ", maxSplits: 1)
                      .map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.characters.split(separator: " ", omittingEmptySubsequences: false)
                      .map(String.init))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Parameters: separator: The element that should be split upon. maxSplits: The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each consecutive pair of separator elements in the collection and for each instance of separator at the start or end of the collection. If true, only nonempty subsequences are returned. The default value is true. Returns: An array of subsequences, split from this collection's elements.

Declaration

func split(separator: UInt8, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [UnsafeMutableRawBufferPointer]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func split(_:omittingEmptySubsequences:whereSeparator:)

Returns the longest possible subsequences of the collection, in order, that don't contain elements satisfying the given predicate.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.characters.split(whereSeparator: { $0 == " " })
                     .map(String.init))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(
    line.characters.split(
        maxSplits: 1, whereSeparator: { $0 == " " }
        ).map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " })
                      .map(String.init))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Parameters: maxSplits: The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the isSeparator predicate and for each element at the start or end of the collection satisfying the isSeparator predicate. The default value is true. isSeparator: A closure that takes an element as an argument and returns a Boolean value indicating whether the collection should be split at that element. Returns: An array of subsequences, split from this collection's elements.

Declaration

func split(maxSplits: Int = default, omittingEmptySubsequences: Bool = default, whereSeparator isSeparator: (UInt8) throws -> Bool) rethrows -> [UnsafeMutableRawBufferPointer]

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func starts(with:)

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

This example tests whether one countable range begins with the elements of another countable range.

let a = 1...3
let b = 1...10

print(b.starts(with: a))
// Prints "true"

Passing an sequence with no elements or an empty collection as possiblePrefix always results in true.

print(b.starts(with: []))
// Prints "true"

possiblePrefix: A sequence to compare to this sequence. Returns: true if the initial elements of the sequence are the same as the elements of possiblePrefix; otherwise, false. If possiblePrefix has no elements, the return value is true.

See Also: starts(with:by:)

Declaration

func starts<PossiblePrefix where PossiblePrefix : Sequence, PossiblePrefix.Iterator.Element == Iterator.Element>(with possiblePrefix: PossiblePrefix) -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func starts(with:by:)

Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.

The predicate must be a equivalence relation over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areEquivalent(a, a) is always true. (Reflexivity)
  • areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry)
  • If areEquivalent(a, b) and areEquivalent(b, c) are both true, then areEquivalent(a, c) is also true. (Transitivity)

Parameters: possiblePrefix: A sequence to compare to this sequence. areEquivalent: A predicate that returns true if its two arguments are equivalent; otherwise, false. Returns: true if the initial elements of the sequence are equivalent to the elements of possiblePrefix; otherwise, false. If possiblePrefix has no elements, the return value is true.

See Also: starts(with:)

Declaration

func starts<PossiblePrefix where PossiblePrefix : Sequence, PossiblePrefix.Iterator.Element == Iterator.Element>(with possiblePrefix: PossiblePrefix, by areEquivalent: (UInt8, UInt8) throws -> Bool) rethrows -> Bool

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func storeBytes(of:toByteOffset:as:)

Stores a value's bytes into raw memory at self + offset.

Precondition: offset + MemoryLayout<T>.size < self.count

Precondition: The underlying pointer plus offset is properly aligned for storing type T.

Precondition: T is a trivial type.

Precondition: The memory is uninitialized, or initialized to some trivial type U such that T and U are mutually layout compatible.

Postcondition: The memory is initialized to raw bytes. If the memory is bound to type U, then it now contains a value of type U.

Note: A trivial type can be copied with just a bit-for-bit copy without any indirection or reference-counting operations. Generally, native Swift types that do not contain strong or weak references or other forms of indirection are trivial, as are imported C structs and enums.

Declaration

func storeBytes<T>(of value: T, toByteOffset offset: Int = default, as: T.Type)
func suffix(_:)

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero. Returns: A subsequence terminating at the end of the collection with at most maxLength elements.

Complexity: O(n), where n is the length of the collection.

Declaration

func suffix(_ maxLength: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection, Sequence
func suffix(from:)

Returns a subsequence from the specified position to the end of the collection.

The following example searches for the index of the number 40 in an array of integers, and then prints the suffix of the array starting at that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.index(of: 40) {
    print(numbers.suffix(from: i))
}
// Prints "[40, 50, 60]"

Passing the collection's endIndex as the start parameter results in an empty subsequence.

print(numbers.suffix(from: numbers.endIndex))
// Prints "[]"

start: The index at which to start the resulting subsequence. start must be a valid index of the collection. Returns: A subsequence starting at the start position.

Complexity: O(1)

Declaration

func suffix(from start: Int) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, Collection, BidirectionalCollection

Conditionally Inherited Items

The initializers, methods, and properties listed below may be available on this type under certain conditions (such as methods that are available on Array when its elements are Equatable) or may not ever be available if that determination is beyond SwiftDoc.org's capabilities. Please open an issue on GitHub if you see something out of place!

Where Index : Strideable, Index.Stride : SignedInteger

subscript(_: CountableClosedRange<Int>)

Accesses a contiguous subrange of the collection's elements.

The accessed slice uses the same indices for the same elements as the original collection. Always use the slice's startIndex property instead of assuming that its indices start at a particular value.

This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print(streetsSlice)
// Prints "["Channing", "Douglas", "Evarts"]"

let index = streetsSlice.index(of: "Evarts")    // 4
streets[index!] = "Eustace"
print(streets[index!])
// Prints "Eustace"

bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Declaration

subscript(bounds: CountableClosedRange<Int>) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable
subscript(_: CountableRange<Int>)

Accesses a contiguous subrange of the collection's elements.

The accessed slice uses the same indices for the same elements as the original collection. Always use the slice's startIndex property instead of assuming that its indices start at a particular value.

This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print(streetsSlice)
// Prints "["Channing", "Douglas", "Evarts"]"

let index = streetsSlice.index(of: "Evarts")    // 4
streets[index!] = "Eustace"
print(streets[index!])
// Prints "Eustace"

bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Declaration

subscript(bounds: CountableRange<Int>) -> UnsafeMutableRawBufferPointer

Declared In

MutableCollection, RandomAccessCollection, MutableIndexable, Collection, RandomAccessIndexable, BidirectionalCollection, Indexable, BidirectionalIndexable

Where Index : Strideable, Index.Stride == IndexDistance, Indices == CountableRange

var indices: CountableRange<Int>

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: CountableRange<Int> { get }

Declared In

RandomAccessCollection
func distance(from:to:)

Returns the distance between two indices.

Parameters: start: A valid index of the collection. end: Another valid index of the collection. If end is equal to start, the result is zero. Returns: The distance between start and end.

Complexity: O(1)

Declaration

func distance(from start: Int, to end: Int) -> IntDistance

Declared In

RandomAccessCollection
func index(_:offsetBy:)

Returns an index that is the specified distance from the given index.

The following example obtains an index advanced four positions from an array's starting index and then prints the element at that position.

let numbers = [10, 20, 30, 40, 50]
let i = numbers.index(numbers.startIndex, offsetBy: 4)
print(numbers[i])
// Prints "50"

The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection.

Parameters: i: A valid index of the collection. n: The distance to offset i. Returns: An index offset by n from the index i. If n is positive, this is the same value as the result of n calls to index(after:). If n is negative, this is the same value as the result of -n calls to index(before:).

Precondition: - If n > 0, n <= self.distance(from: i, to: self.endIndex) - If n < 0, n >= self.distance(from: i, to: self.startIndex) Complexity: O(1)

Declaration

func index(_ i: Int, offsetBy n: IntDistance) -> Int

Declared In

RandomAccessCollection
func index(after:)

Returns the position immediately after the given index.

i: A valid index of the collection. i must be less than endIndex. Returns: The index value immediately after i.

Declaration

func index(after i: Int) -> Int

Declared In

RandomAccessCollection
func index(before:)

Returns the position immediately after the given index.

i: A valid index of the collection. i must be greater than startIndex. Returns: The index value immediately before i.

Declaration

func index(before i: Int) -> Int

Declared In

RandomAccessCollection

Where Indices == DefaultBidirectionalIndices

var indices: DefaultBidirectionalIndices<UnsafeMutableRawBufferPointer>

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: DefaultBidirectionalIndices<UnsafeMutableRawBufferPointer> { get }

Declared In

RandomAccessCollection , BidirectionalCollection

Where Indices == DefaultIndices

var indices: DefaultIndices<UnsafeMutableRawBufferPointer>

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: DefaultIndices<UnsafeMutableRawBufferPointer> { get }

Declared In

MutableCollection , RandomAccessCollection , Collection , BidirectionalCollection

Where Indices == DefaultRandomAccessIndices

var indices: DefaultRandomAccessIndices<UnsafeMutableRawBufferPointer>

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: DefaultRandomAccessIndices<UnsafeMutableRawBufferPointer> { get }

Declared In

RandomAccessCollection