UnsafeMutableRawBufferPointer

struct UnsafeMutableRawBufferPointer

A mutable nonowning collection interface to the bytes in a region of memory.

Inheritance CustomDebugStringConvertible, MutableCollection, Sequence
Associated Types
public typealias Iterator = UnsafeRawBufferPointer.Iterator
public typealias Element = UInt8
public typealias Index = Int

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.

public typealias Indices = Range<Int>
public typealias SubSequence = Slice<UnsafeMutableRawBufferPointer>

This associated type appears as a requirement in the Sequence protocol, but it is restated here with stricter constraints. In a collection, the subsequence should also conform to Collection.

You can use an UnsafeMutableRawBufferPointer instance in low-level operations to eliminate uniqueness checks and release mode bounds checks. Bounds checks are always performed in debug mode.

An UnsafeMutableRawBufferPointer instance is a view of the raw bytes in a region of memory. Each byte in memory is viewed as a UInt8 value independent of the type of values held in that memory. Reading from and writing to memory through a raw buffer are untyped operations. Accessing this collection's bytes does not bind the underlying memory to UInt8.

In addition to its collection interface, an UnsafeMutableRawBufferPointer instance also supports the following methods provided by UnsafeMutableRawPointer, including bounds checks in debug mode:

To access the underlying memory through typed operations, the memory must be bound to a trivial type.

Note: A trivial type can be copied bit for bit with no 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 types 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().

UnsafeMutableRawBufferPointer Semantics

An UnsafeMutableRawBufferPointer instance is a view into memory and does not own the memory that it references. Copying a variable or constant of type UnsafeMutableRawBufferPointer does not copy the underlying memory. However, initializing another collection with an UnsafeMutableRawBufferPointer instance copies bytes out of the referenced memory and into the new collection.

The following example uses someBytes, an UnsafeMutableRawBufferPointer instance, to demonstrate the difference between assigning a buffer pointer and using a buffer pointer as the source for another collection's elements. Here, the assignment to destBytes creates a new, nonowning buffer pointer covering the first n bytes of the memory that someBytes references---nothing is copied:

var destBytes = someBytes[0..<n]

Next, the bytes referenced by destBytes are copied into byteArray, a new [UInt] array, and then the remainder of someBytes is appended to byteArray:

var byteArray: [UInt8] = Array(destBytes)
byteArray += someBytes[n..<someBytes.count]

Assigning into a ranged subscript of an UnsafeMutableRawBufferPointer instance copies bytes into the memory. The next n bytes of the memory that someBytes references are copied in this code:

destBytes[0..<n] = someBytes[n..<(n + n)]

Initializers

init init(_:) Required

Creates a new buffer over the same memory as the given buffer.

  • Parameter bytes: The buffer to convert.

Declaration

@inlinable public init(_ bytes: UnsafeMutableRawBufferPointer)
init init(_:) Required

Creates a raw buffer over the contiguous bytes in the given typed buffer.

  • Parameter buffer: The typed buffer to convert to a raw buffer. The buffer's type T must be a trivial type.

Declaration

@inlinable public init<T>(_ buffer: UnsafeMutableBufferPointer<T>)
init init(mutating:) Required

Creates a new mutable buffer over the same memory as the given buffer.

  • Parameter bytes: The buffer to convert.

Declaration

@inlinable public init(mutating bytes: UnsafeRawBufferPointer)
init init(rebasing:) Required

Creates a raw buffer over the same memory as the given raw buffer slice, with the indices rebased to zero.

The new buffer represents the same region of memory as the slice, but its indices start at zero instead of at the beginning of the slice in the original buffer. The following code creates slice, a slice covering part of an existing buffer instance, then rebases it into a new rebased buffer.

let slice = buffer[n...]
let rebased = UnsafeRawBufferPointer(rebasing: slice)

After this code has executed, the following are true:

  • Parameter slice: The raw buffer slice to rebase.

Declaration

@inlinable public init(rebasing slice: Slice<UnsafeMutableRawBufferPointer>)
init init(start:count:) Required

Creates a buffer over the specified number of contiguous bytes starting at the given pointer.

Declaration

@inlinable public init(start: UnsafeMutableRawPointer?, count: Int)

Instance Variables

var baseAddress Required

A pointer to the first byte of the buffer.

If the baseAddress of this buffer is nil, the count is zero. However, a buffer can have a count of zero even with a non-nil base address.

Declaration

var baseAddress: UnsafeMutableRawPointer?
var count Required

The number of bytes in the buffer.

If the baseAddress of this buffer is nil, the count is zero. However, a buffer can have a count of zero even with a non-nil base address.

Declaration

var count: Int
var debugDescription Required

A textual representation of the buffer, suitable for debugging.

Declaration

var debugDescription: String
var endIndex Required

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: UnsafeMutableRawBufferPointer.Index
var indices Required

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 nonuniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can result in 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
var lazy Required

A sequence containing the same elements as this sequence, but on which some operations, such as map and filter, are implemented lazily.

Declaration

var lazy: LazySequence<Self>
var startIndex Required

Always zero, which is the index of the first byte in a nonempty buffer.

Declaration

var startIndex: UnsafeMutableRawBufferPointer.Index
var underestimatedCount Required

A value less than or equal to the number of elements in the sequence, calculated nondestructively.

The default implementation returns 0. If you provide your own implementation, make sure to compute the value nondestructively.

Complexity: O(1), except if the sequence also conforms to Collection. In this case, see the documentation of Collection.underestimatedCount.

Declaration

var underestimatedCount: Int

Subscripts

subscript subscript(bounds:) Required

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.firstIndex(of: "Evarts")    // 4
streets[index!] = "Eustace"
print(streets[index!])
// Prints "Eustace"
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@inlinable public subscript(bounds: Range<Self.Index>) -> Slice<Self>
subscript subscript(r:) Required

Declaration

@inlinable public subscript<R>(r: R) where R: RangeExpression, Self.Index == R.Bound -> Self.SubSequence
subscript subscript(x:) Required

Declaration

@inlinable public subscript(x: (UnboundedRange_) -> ()) -> Self.SubSequence

Instance Methods

func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool Required

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

The following code uses this method to test whether all the names in an array have at least five characters:

let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
// allHaveAtLeastFive == true
  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition.

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

Declaration

@inlinable public func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool
func bindMemory(to type: T.Type) -> UnsafeMutableBufferPointer<T> Required

Binds this buffer’s memory to the specified type and returns a typed buffer of the bound memory.

Use the bindMemory(to:) method to bind the memory referenced by this buffer to the type T. The memory must be uninitialized or initialized to a type that is layout compatible with T. If the memory is uninitialized, it is still uninitialized after being bound to T.

Warning: A memory location may only be bound to one type at a time. The behavior of accessing memory as a type unrelated to its bound type is undefined.

Declaration

public func bindMemory<T>(to type: T.Type) -> UnsafeMutableBufferPointer<T>
func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] Required

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 non-optional values when your transformation produces an optional value.

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

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

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

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]
  • Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.

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

Declaration

@inlinable public func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool Required

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
  • Parameter 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.

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

Declaration

@inlinable public func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool
func copyBytes(from source: C) Required

Copies from a collection of UInt8 into this buffer's memory.

If the source.count bytes of memory referenced by this buffer are bound to a type T, then T must be a trivial type, the underlying pointer must be properly aligned for accessing T, and source.count must be a multiple of MemoryLayout<T>.stride.

After calling copyBytes(from:), the source.count bytes of memory referenced by this buffer are initialized to raw bytes. If the memory is bound to type T, then it contains values of type T.

  • Parameter source: A collection of UInt8 elements. source.count must be less than or equal to this buffer's count.

Declaration

@inlinable public func copyBytes<C>(from source: C) where C: Collection, C.Element == UInt8
func copyMemory(from source: UnsafeRawBufferPointer) Required

Copies the bytes from the given buffer to this buffer's memory.

If the source.count bytes of memory referenced by this buffer are bound to a type T, then T must be a trivial type, the underlying pointer must be properly aligned for accessing T, and source.count must be a multiple of MemoryLayout<T>.stride.

The memory referenced by source may overlap with the memory referenced by this buffer.

After calling copyMemory(from:), the first source.count bytes of memory referenced by this buffer are initialized to raw bytes. If the memory is bound to type T, then it contains values of type T.

  • Parameter source: A buffer of raw bytes from which to copy. source.count must be less than or equal to this buffer's count.

Declaration

@inlinable public func copyMemory(from source: UnsafeRawBufferPointer)
func deallocate() Required

Deallocates the memory block previously allocated at this buffer pointer’s base address.

This buffer pointer's baseAddress must be nil or a pointer to a memory block previously returned by a Swift allocation method. If baseAddress is nil, this function does nothing. Otherwise, the memory must not be initialized or Pointee must be a trivial type. This buffer pointer's byte count must be equal to the originally allocated size of the memory block.

Declaration

@inlinable public func deallocate()
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> DropWhileSequence<Self> Required

Returns a sequence by skipping the initial, consecutive elements that satisfy the given predicate.

The following example uses the drop(while:) method to skip over the positive numbers at the beginning of the numbers array. The result begins with the first element of numbers that does not satisfy predicate.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let startingWithNegative = numbers.drop(while: { $0 > 0 })
// startingWithNegative == [-2, 9, -6, 10, 1]

If predicate matches every element in the sequence, the result is an empty sequence.

  • Parameter predicate: 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 result.

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

Declaration

@inlinable public func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> DropWhileSequence<Self>
func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> Required

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

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"
  • Parameter k: The number of elements to drop from the beginning of the sequence. k must be greater than or equal to zero.

Complexity: O(1), with O(k) deferred to each iteration of the result, where k is the number of elements to drop from the beginning of the sequence.

Declaration

@inlinable public func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self>
func dropLast(_ k: Int = 1) -> [Self.Element] Required

Returns a sequence containing all but the given number of final elements.

The sequence must be finite. If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter n: The number of elements to drop off the end of the sequence. n must be greater than or equal to zero.

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

Declaration

@inlinable public func dropLast(_ k: Int = 1) -> [Self.Element]
func elementsEqual(_ other: OtherSequence, by areEquivalent: (Self.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool Required

Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, 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:

Complexity: O(m), where m is the lesser of the length of the sequence and the length of other.

Declaration

@inlinable public func elementsEqual<OtherSequence>(_ other: OtherSequence, by areEquivalent: (Self.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool where OtherSequence: Sequence
func enumerated() -> EnumeratedSequence<Self> Required

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".enumerated() {
    print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"

When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only 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 consisting of indices of names with five or fewer letters.

let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [Set<String>.Index] = []
for (i, name) in zip(names.indices, names) {
    if name.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"

Complexity: O(1)

Declaration

@inlinable public func enumerated() -> EnumeratedSequence<Self>
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element] Required

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.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"
  • Parameter isIncluded: 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.

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

Declaration

@inlinable public func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element? Required

Returns the first element of the sequence that satisfies the given predicate.

The following example uses the first(where:) method to find the first negative number in an array of integers:

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
    print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."
  • Parameter 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.

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

Declaration

@inlinable public func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?
func flatMap(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] Required

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(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

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

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

  • Parameter transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection.

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

Declaration

@inlinable public func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult: Sequence
func flatMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] Required

Declaration

@available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value") public func flatMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
func forEach(_ body: (Self.Element) throws -> Void) rethrows Required

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.
  • Parameter body: A closure that takes an element of the sequence as a parameter.

Declaration

@inlinable public func forEach(_ body: (Self.Element) throws -> Void) rethrows
func initializeMemory(as type: S.Element.Type, from source: S) -> (unwritten: S.Iterator, initialized: UnsafeMutableBufferPointer<S.Element>) Required

Initializes the buffer's memory with the given elements, binding the initialized memory to the elements' type.

When calling the initializeMemory(as:from:) method on a buffer b, the memory referenced by b must be uninitialized or initialized to a trivial type, and must be properly aligned for accessing S.Element. The buffer must contain sufficient memory to accommodate source.underestimatedCount.

This method initializes the buffer with elements from source until source is exhausted or, if source is a sequence but not a collection, the buffer has no more room for its elements. After calling initializeMemory(as:from:), the memory referenced by the returned UnsafeMutableBufferPointer instance is bound and initialized to type S.Element.

Declaration

@inlinable public func initializeMemory<S>(as type: S.Element.Type, from source: S) -> (unwritten: S.Iterator, initialized: UnsafeMutableBufferPointer<S.Element>) where S: Sequence
func initializeMemory(as type: T.Type, repeating repeatedValue: T) -> UnsafeMutableBufferPointer<T> Required

Initializes the memory referenced by this buffer with the given value, binds the memory to the value's type, and returns a typed buffer of the initialized memory.

The memory referenced by this buffer must be uninitialized or initialized to a trivial type, and must be properly aligned for accessing T.

After calling this method on a raw buffer with non-nil baseAddress b, the region starting at b and continuing up to b + self.count - self.count % MemoryLayout<T>.stride is bound to type T and initialized. If T is a nontrivial type, you must eventually deinitialize or move the values in this region to avoid leaks. If baseAddress is nil, this function does nothing and returns an empty buffer pointer.

Declaration

@inlinable public func initializeMemory<T>(as type: T.Type, repeating repeatedValue: T) -> UnsafeMutableBufferPointer<T>
func lexicographicallyPrecedes(_ other: OtherSequence, by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Bool Required

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:

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.

Complexity: O(m), where m is the lesser of the length of the sequence and the length of other.

Declaration

@inlinable public func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence, by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Bool where OtherSequence: Sequence, Self.Element == OtherSequence.Element
func load(fromByteOffset offset: Int = 0, as type: T.Type) -> T Required

Returns a new instance of the given type, read from the buffer pointer's raw memory at the specified byte offset.

You can use this method to create new values from the buffer pointer's underlying bytes. The following example creates two new Int32 instances from the memory referenced by the buffer pointer someBytes. The bytes for a are copied from the first four bytes of someBytes, and the bytes for b are copied from the next four bytes.

let a = someBytes.load(as: Int32.self)
let b = someBytes.load(fromByteOffset: 4, as: Int32.self)

The memory to read for the new instance must not extend beyond the buffer pointer's memory region---that is, offset + MemoryLayout<T>.size must be less than or equal to the buffer pointer's count.

Declaration

@inlinable public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T
func makeIterator() -> UnsafeMutableRawBufferPointer.Iterator Required

Returns an iterator over the bytes of this sequence.

Declaration

@inlinable public func makeIterator() -> UnsafeMutableRawBufferPointer.Iterator
func map(_ transform: (Self.Element) throws -> T) rethrows -> [T] Required

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.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]
  • Parameter 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.

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

Declaration

@inlinable public func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
func max(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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:

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))"
  • Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

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

Declaration

@warn_unqualified_access @inlinable public func max(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?
func min(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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:

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))"
  • Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

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

Declaration

@warn_unqualified_access @inlinable public func min(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?
func partition(by belongsInSecondPartition: (Self.Element) throws -> Bool) rethrows -> Self.Index Required

Reorders the elements of the collection such that all the elements that match the given predicate are after all the elements that don't match.

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[..<p], is made up of the elements that are not greater than 30. The second partition, numbers[p...], is made up of the elements that are greater than 30.

let first = numbers[..<p]
// first == [30, 10, 20, 30, 30]
let second = numbers[p...]
// second == [60, 40]
  • Parameter belongsInSecondPartition: A predicate used to partition the collection. All elements satisfying this predicate are ordered after all elements not satisfying it.

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

Declaration

@inlinable public mutating func partition(by belongsInSecondPartition: (Self.Element) throws -> Bool) rethrows -> Self.Index
func prefix(_ maxLength: Int) -> PrefixSequence<Self> Required

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

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

Complexity: O(1)

Declaration

@inlinable public func prefix(_ maxLength: Int) -> PrefixSequence<Self>
func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> [Self.Element] Required

Returns a sequence containing the initial, consecutive elements that satisfy the given predicate.

The following example uses the prefix(while:) method to find the positive numbers at the beginning of the numbers array. Every element of numbers up to, but not including, the first negative value is included in the result.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let positivePrefix = numbers.prefix(while: { $0 > 0 })
// positivePrefix == [3, 7, 4]

If predicate matches every element in the sequence, the resulting sequence contains every element of the sequence.

  • Parameter predicate: 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 result.

Complexity: O(k), where k is the length of the result.

Declaration

@inlinable public func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result Required

Returns the result of combining the elements of the sequence using the given closure.

Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.

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 numberSum = numbers.reduce(0, { x, y in
    x + y
})
// numberSum == 10

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

  1. The nextPartialResult closure is called with initialResult---0 in this case---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.

If the sequence has no elements, nextPartialResult is never executed and initialResult is the result of the call to reduce(_:_:).

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

Declaration

@inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result
func reduce(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()) rethrows -> Result Required

Returns the result of combining the elements of the sequence using the given closure.

Use the reduce(into:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies.

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

The updateAccumulatingResult closure is called sequentially with a mutable accumulating value initialized to initialResult and each element of the sequence. This example shows how to build a dictionary of letter frequencies of a string.

let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
    counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]

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

  1. The updateAccumulatingResult closure is called with the initial accumulating value---[:] in this case---and the first character of letters, modifying the accumulating value by setting 1 for the key "a".
  2. The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
  3. When the sequence is exhausted, the accumulating value is returned to the caller.

If the sequence has no elements, updateAccumulatingResult is never executed and initialResult is the result of the call to reduce(into:_:).

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

Declaration

@inlinable public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()) rethrows -> Result
func reversed() -> [Self.Element] Required

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.

Declaration

@inlinable public func reversed() -> [Self.Element]
func shuffled() -> [Self.Element] Required

Returns the elements of the sequence, shuffled.

For example, you can shuffle the numbers between 0 and 9 by calling the shuffled() method on that range:

let numbers = 0...9
let shuffledNumbers = numbers.shuffled()
// shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]

This method is equivalent to calling shuffled(using:), passing in the system's default random generator.

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

Declaration

@inlinable public func shuffled() -> [Self.Element]
func shuffled(using generator: inout T) -> [Self.Element] Required

Returns the elements of the sequence, shuffled using the given generator as a source for randomness.

You use this method to randomize the elements of a sequence when you are using a custom random number generator. For example, you can shuffle the numbers between 0 and 9 by calling the shuffled(using:) method on that range:

let numbers = 0...9
let shuffledNumbers = numbers.shuffled(using: &myGenerator)
// shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]
  • Parameter generator: The random number generator to use when shuffling the sequence.

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

Note: The algorithm used to shuffle a sequence may change in a future version of Swift. If you're passing a generator that results in the same shuffled order each time you run your program, that sequence may change when your program is compiled using a different version of Swift.

Declaration

@inlinable public func shuffled<T>(using generator: inout T) -> [Self.Element] where T: RandomNumberGenerator
func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element] Required

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

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

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 sequence 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"]"

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:

The sorting algorithm is not guaranteed to be stable. A stable sort preserves the relative order of elements for which areInIncreasingOrder does not establish an order.

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

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

Declaration

@inlinable public func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element]
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [ArraySlice<Self.Element>] Required

Returns the longest possible subsequences of the sequence, in order, that don't contain elements satisfying the given predicate. 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.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.split(maxSplits: 1, whereSeparator: { $0 == " " })
                  .map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

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

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

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

Declaration

@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [ArraySlice<Self.Element>]
func starts(with possiblePrefix: PossiblePrefix, by areEquivalent: (Self.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool Required

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:

Complexity: O(m), where m is the lesser of the length of the sequence and the length of possiblePrefix.

Declaration

@inlinable public func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix, by areEquivalent: (Self.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool where PossiblePrefix: Sequence
func storeBytes(of value: T, toByteOffset offset: Int = 0, as: T.Type) Required

Stores a value's bytes into the buffer pointer's raw memory at the specified byte offset.

The type T to be stored must be a trivial type. The memory must also be uninitialized, initialized to T, or initialized to another trivial type that is layout compatible with T.

The memory written to must not extend beyond the buffer pointer's memory region---that is, offset + MemoryLayout<T>.size must be less than or equal to the buffer pointer's count.

After calling storeBytes(of:toByteOffset:as:), the memory is initialized to the raw bytes of value. If the memory is bound to a type U that is layout compatible with T, then it contains a value of type U. Calling storeBytes(of:toByteOffset:as:) does not change the bound type of the memory.

Declaration

@inlinable public func storeBytes<T>(of value: T, toByteOffset offset: Int = 0, as: T.Type)
func suffix(_ maxLength: Int) -> [Self.Element] Required

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

The sequence must be finite. If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

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

Declaration

@inlinable public func suffix(_ maxLength: Int) -> [Self.Element]
func swapAt(_ i: Int, _ j: Int) Required

Exchanges the byte values at the specified indices in this buffer's memory.

Both parameters must be valid indices of the buffer, and not equal to endIndex. Passing the same index as both i and j has no effect.

Declaration

@inlinable public func swapAt(_ i: Int, _ j: Int)
func swapAt(_ i: Self.Index, _ j: Self.Index) Required

Exchanges the values at the specified indices of the collection.

Both parameters must be valid indices of the collection that are not equal to endIndex. Calling swapAt(_:_:) with the same index as both i and j has no effect.

Complexity: O(1)

Declaration

@inlinable public mutating func swapAt(_ i: Self.Index, _ j: Self.Index)
func withContiguousMutableStorageIfAvailable(_ body: (inout UnsafeMutableBufferPointer<Self.Element>) throws -> R) rethrows -> R? Required

Call body(p), where p is a pointer to the collection's mutable contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of mutable contiguous storage, body is not called and nil is returned.

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

Declaration

@inlinable public mutating func withContiguousMutableStorageIfAvailable<R>(_ body: (inout UnsafeMutableBufferPointer<Self.Element>) throws -> R) rethrows -> R?
func withContiguousStorageIfAvailable(_ body: (UnsafeBufferPointer<Self.Element>) throws -> R) rethrows -> R? Required

Call body(p), where p is a pointer to the collection's contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

A Collection that provides its own implementation of this method must also guarantee that an equivalent buffer of its SubSequence can be generated by advancing the pointer by the distance to the slice's startIndex.

Declaration

@inlinable public func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<Self.Element>) throws -> R) rethrows -> R?

Type Methods

func allocate(byteCount: Int, alignment: Int) -> UnsafeMutableRawBufferPointer Required

Returns a newly allocated buffer with the given size, in bytes.

The memory referenced by the new buffer is allocated, but not initialized.

Declaration

@inlinable public static func allocate(byteCount: Int, alignment: Int) -> UnsafeMutableRawBufferPointer