CollectionOfOne

struct CollectionOfOne

A collection containing a single element.

Inheritance CustomDebugStringConvertible, CustomReflectable, MutableCollection, RandomAccessCollection
Associated Types
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<CollectionOfOne<Element>>

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.

Nested Types CollectionOfOne.Iterator

You can use a CollectionOfOne instance when you need to efficiently represent a single value as a collection. For example, you can add a single element to an array by using a CollectionOfOne instance with the concatenation operator (+):

let a = [1, 2, 3, 4]
let toAdd = 100
let b = a + CollectionOfOne(toAdd)
// b == [1, 2, 3, 4, 100]

Initializers

init init(_:) Required

Creates an instance containing just the given element.

  • Parameter element: The element to store in the collection.

Declaration

@inlinable public init(_ element: Element)

Instance Variables

var count Required

The number of elements in the collection, which is always one.

Declaration

var count: Int
var customMirror Required

The custom mirror for this instance.

If this type has value semantics, the mirror should be unaffected by subsequent mutations of the instance.

Declaration

var customMirror: Mirror
var debugDescription Required

A textual representation of the collection, 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.

In a CollectionOfOne instance, endIndex is always 1.

Declaration

var endIndex: CollectionOfOne<Element>.Index
var startIndex Required

The position of the first element.

In a CollectionOfOne instance, startIndex is always 0.

Declaration

var startIndex: CollectionOfOne<Element>.Index

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(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 uses. 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
print(streets[index!])
// Prints "Evarts"
  • 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<Int>) -> CollectionOfOne<Element>.SubSequence
subscript subscript(position:) Required

Accesses the element at the specified position.

  • Parameter position: The position of the element to access. The only valid position in a CollectionOfOne instance is 0.

Declaration

@inlinable public subscript(position: Int) -> Element
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 index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index? Required

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 an array's starting index and then prints the element at that position. The operation doesn't require going beyond the limiting numbers.endIndex value, so it succeeds.

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

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

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

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1)

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
func index(after i: CollectionOfOne<Element>.Index) -> CollectionOfOne<Element>.Index Required

Returns the position immediately after the given index.

  • Parameter i: A valid index of the collection. i must be 0.

Declaration

@inlinable public func index(after i: CollectionOfOne<Element>.Index) -> CollectionOfOne<Element>.Index
func index(before i: CollectionOfOne<Element>.Index) -> CollectionOfOne<Element>.Index Required

Returns the position immediately before the given index.

  • Parameter i: A valid index of the collection. i must be 1.

Declaration

@inlinable public func index(before i: CollectionOfOne<Element>.Index) -> CollectionOfOne<Element>.Index
func makeIterator() -> CollectionOfOne<Element>.Iterator Required

Returns an iterator over the elements of this collection.

Complexity: O(1)

Declaration

@inlinable public func makeIterator() -> CollectionOfOne<Element>.Iterator
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 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?