LazyCollectionProtocol

protocol LazyCollectionProtocol
Inheritance Collection, LazySequenceProtocol

Default Implementations

func compactMap(_ transform: @escaping (Self.Elements.Element) -> ElementOfResult?) -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Self.Elements, ElementOfResult?>>, ElementOfResult>

Returns the non-nil results of mapping the given transformation over this sequence.

Use this method to receive a sequence of non-optional values when your transformation produces an optional value.

  • Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.

Complexity: O(1)

Declaration

@inlinable public func compactMap<ElementOfResult>(_ transform: @escaping (Self.Elements.Element) -> ElementOfResult?) -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Self.Elements, ElementOfResult?>>, ElementOfResult>
var count

The number of elements in the collection.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Unless the collection guarantees random-access performance, calculating count can be an O(n) operation.

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

Declaration

var count: Int
func distance(from start: Self.Index, to end: Self.Index) -> Int

Returns the distance between two indices.

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

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

Declaration

@inlinable public func distance(from start: Self.Index, to end: Self.Index) -> Int
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be skipped or false if it should be included. Once the predicate returns false it will not be called again.

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

Declaration

@inlinable public func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func drop(while predicate: @escaping (Self.Elements.Element) -> Bool) -> LazyDropWhileSequence<Self.Elements>

Returns a lazy sequence that skips any initial elements that satisfy predicate.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be skipped or false otherwise. Once predicate returns false it will not be called again.

Declaration

@inlinable public func drop(while predicate: @escaping (Self.Elements.Element) -> Bool) -> LazyDropWhileSequence<Self.Elements>
func dropFirst(_ k: Int = 1) -> Self.SubSequence

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 "[]"
  • Parameter k: The number of elements to drop from the beginning of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop from the beginning of the collection.

Declaration

@inlinable public func dropFirst(_ k: Int = 1) -> Self.SubSequence
func dropLast(_ k: Int = 1) -> Self.SubSequence

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 "[]"
  • Parameter k: The number of elements to drop off the end of the collection. k must be greater than or equal to zero.

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

Declaration

@inlinable public func dropLast(_ k: Int = 1) -> Self.SubSequence
func filter(_ isIncluded: @escaping (Self.Elements.Element) -> Bool) -> LazyFilterSequence<Self.Elements>

Returns the elements of self that satisfy isIncluded.

Note: The elements of the result are computed on-demand, as the result is used. No buffering storage is allocated and each traversal step invokes predicate on one or more underlying elements.

Declaration

@inlinable public func filter(_ isIncluded: @escaping (Self.Elements.Element) -> Bool) -> LazyFilterSequence<Self.Elements>
var first

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: Self.Element?
func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?

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.firstIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"
  • Parameter predicate: A closure that takes an element 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 collection.

Declaration

@inlinable public func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
func flatMap(_ transform: @escaping (Self.Elements.Element) -> SegmentOfResult) -> LazySequence<FlattenSequence<LazyMapSequence<Self.Elements, SegmentOfResult>>>

Returns the concatenated results of mapping the given transformation over this sequence.

Use this method to receive a single-level sequence when your transformation produces a sequence or collection for each element. Calling flatMap(_:) on a sequence s is equivalent to calling s.map(transform).joined().

Complexity: O(1)

Declaration

@inlinable public func flatMap<SegmentOfResult>(_ transform: @escaping (Self.Elements.Element) -> SegmentOfResult) -> LazySequence<FlattenSequence<LazyMapSequence<Self.Elements, SegmentOfResult>>> where SegmentOfResult: Sequence
func flatMap(_ transform: @escaping (Self.Elements.Element) -> ElementOfResult?) -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Self.Elements, ElementOfResult?>>, ElementOfResult>

Returns the non-nil results of mapping the given transformation over this sequence.

Use this method to receive a sequence of non-optional values when your transformation produces an optional value.

  • Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.

Complexity: O(1)

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: @escaping (Self.Elements.Element) -> ElementOfResult?) -> LazyMapSequence<LazyFilterSequence<LazyMapSequence<Self.Elements, ElementOfResult?>>, ElementOfResult>
func formIndex(_ i: inout Self.Index, offsetBy distance: Int)

Offsets the given index by the specified distance.

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int)
func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool

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

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) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool
func formIndex(after i: inout Self.Index)

Replaces the given index with its successor.

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

Declaration

@inlinable public func formIndex(after i: inout Self.Index)
func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index

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 distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

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

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 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) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
var isEmpty

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.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
var lazy

Declaration

var lazy: LazySequence<Self.Elements>
func map(_ transform: (Self.Element) throws -> T) rethrows -> [T]

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.

Declaration

@inlinable public func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
func map(_ transform: @escaping (Self.Element) -> U) -> LazyMapSequence<Self.Elements, U>

Returns a LazyMapSequence over this Sequence. The elements of the result are computed lazily, each time they are read, by calling transform function on a base element.

Declaration

@inlinable public func map<U>(_ transform: @escaping (Self.Element) -> U) -> LazyMapSequence<Self.Elements, U>
func prefix(_ maxLength: Int) -> Self.SubSequence

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]"
  • Parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.

Declaration

@inlinable public func prefix(_ maxLength: Int) -> Self.SubSequence
func prefix(through position: Self.Index) -> Self.SubSequence

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.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection's subscript. The subscript notation is preferred over prefix(through:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"
  • Parameter 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.

Complexity: O(1)

Declaration

@inlinable public func prefix(through position: Self.Index) -> Self.SubSequence
func prefix(upTo end: Self.Index) -> Self.SubSequence

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.firstIndex(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 "[]"

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[..<i])
}
// Prints "[10, 20, 30]"
  • Parameter end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func prefix(upTo end: Self.Index) -> Self.SubSequence
func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be included or false if it should be excluded. Once the predicate returns false it will not be called again.

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

Declaration

@inlinable public func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func prefix(while predicate: @escaping (Self.Elements.Element) -> Bool) -> LazyPrefixWhileSequence<Self.Elements>

Returns a lazy sequence of the initial consecutive elements that satisfy predicate.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be included or false otherwise. Once predicate returns false it will not be called again.

Declaration

@inlinable public func prefix(while predicate: @escaping (Self.Elements.Element) -> Bool) -> LazyPrefixWhileSequence<Self.Elements>
func randomElement() -> Self.Element?

Returns a random element of the collection.

Call randomElement() to select a random element from an array or another collection. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
// randomName == "Amani"

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

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

Declaration

@inlinable public func randomElement() -> Self.Element?
func randomElement(using generator: inout T) -> Self.Element?

Returns a random element of the collection, using the given generator as a source for randomness.

Call randomElement(using:) to select a random element from an array or another collection when you are using a custom random number generator. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement(using: &myGenerator)!
// randomName == "Amani"
  • Parameter generator: The random number generator to use when choosing a random element.

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

Note: The algorithm used to select a random element may change in a future version of Swift. If you're passing a generator that results in the same sequence of elements 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 randomElement<T>(using generator: inout T) -> Self.Element? where T: RandomNumberGenerator
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]

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.split(whereSeparator: { $0 == " " }))
// 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 == " " }))
// 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.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

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

Declaration

@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]
subscript subscript(r:)

Accesses the contiguous subrange of the collection's elements specified by a range expression.

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

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

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

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

Always use the slice's startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice's indices may result in a runtime error, even if that index is valid for the original collection.

print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"

print(streetsSlice[0])
// error: Index out of bounds
  • 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<R>(r: R) where R: RangeExpression, Self.Index == R.Bound -> Self.SubSequence
subscript subscript(x:)

Declaration

@inlinable public subscript(x: (UnboundedRange_) -> ()) -> Self.SubSequence
func suffix(_ maxLength: Int) -> Self.SubSequence

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]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

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

Declaration

@inlinable public func suffix(_ maxLength: Int) -> Self.SubSequence
func suffix(from start: Self.Index) -> Self.SubSequence

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.firstIndex(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 "[]"

Using the suffix(from:) method is equivalent to using a partial range from the index as the collection's subscript. The subscript notation is preferred over suffix(from:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[i...])
}
// Prints "[40, 50, 60]"
  • Parameter start: The index at which to start the resulting subsequence. start must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func suffix(from start: Self.Index) -> Self.SubSequence
var underestimatedCount

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