LazySequenceType

protocol LazySequenceType

A sequence on which normally-eager operations such as map and filter are implemented lazily.

Lazy sequences can be used to avoid needless storage allocation and computation, because they use an underlying sequence for storage and compute their elements on demand. For example,

[1, 2, 3].lazy.map { $0 * 2 }

is a sequence containing { 2, 4, 6 }. Each time an element of the lazy sequence is accessed, an element of the underlying array is accessed and transformed by the closure.

Sequence operations taking closure arguments, such as map and filter, are normally eager: they use the closure immediately and return a new array. Using the lazy property gives the standard library explicit permission to store the closure and the sequence in the result, and defer computation until it is needed.

To add new lazy sequence operations, extend this protocol with methods that return lazy wrappers that are themselves LazySequenceTypes. For example, given an eager scan method defined as follows

extension SequenceType {
  /// Returns an array containing the results of
  ///
  ///   p.reduce(initial, combine: combine)
  ///
  /// for each prefix `p` of `self`, in order from shortest to
  /// longest.  For example:
  ///
  ///     (1..<6).scan(0, combine: +) // [0, 1, 3, 6, 10, 15]
  ///
  /// **Complexity:** O(N)
  func scan<ResultElement>(
    initial: ResultElement,
    @noescape combine: (ResultElement, Generator.Element)->ResultElement
  ) -> [ResultElement] {
    var result = [initial]
    for x in self {
      result.append(combine(result.last!, x))
    }
    return result
  }
}

we can build a sequence that lazily computes the elements in the result of scan:

struct LazyScanGenerator<Base: GeneratorType, ResultElement>
  : GeneratorType {
  mutating func next() -> ResultElement? {
    return nextElement.map { result in
      nextElement = base.next().map { combine(result, $0) }
      return result
    }
  }
  private var nextElement: ResultElement? // The next result of next().
  private var base: Base                  // The underlying generator.
  private let combine: (ResultElement, Base.Element)->ResultElement
}

struct LazyScanSequence<Base: SequenceType, ResultElement>
  : LazySequenceType // Chained operations on self are lazy, too
{
  func generate() -> LazyScanGenerator<Base.Generator, ResultElement> {
    return LazyScanGenerator(
      nextElement: initial, base: base.generate(), combine: combine)
  }
  private let initial: ResultElement
  private let base: Base
  private let combine:
    (ResultElement, Base.Generator.Element)->ResultElement
}

and finally, we can give all lazy sequences a lazy scan method:

extension LazySequenceType {
  /// Returns a sequence containing the results of
  ///
  ///   p.reduce(initial, combine: combine)
  ///
  /// for each prefix `p` of `self`, in order from shortest to
  /// longest.  For example:
  ///
  ///     Array((1..<6).lazy.scan(0, combine: +)) // [0, 1, 3, 6, 10, 15]
  ///
  /// **Complexity:** O(1)
  func scan<ResultElement>(
    initial: ResultElement,
    combine: (ResultElement, Generator.Element)->ResultElement
  ) -> LazyScanSequence<Self, ResultElement> {
    return LazyScanSequence(
      initial: initial, base: self, combine: combine)
  }
}

See Also: LazySequence, LazyCollectionType, LazyCollection

Note: the explicit permission to implement further operations lazily applies only in contexts where the sequence is statically known to conform to LazySequenceType. Thus, side-effects such as the accumulation of result below are never unexpectedly dropped or deferred:

  extension SequenceType where Generator.Element == Int {
    func sum() -> Int {
      var result = 0
      _ = self.map { result += $0 }
      return result
    }
  }

[We don't recommend that you use map this way, because it creates and discards an array. sum would be better implemented using reduce].

Inheritance SequenceType View Protocol Hierarchy →
Associated Types
Elements : SequenceType = Self

A SequenceType that can contain the same elements as this one, possibly with a simpler type.

See Also: elements

Generator : GeneratorType

A type that provides the sequence's iteration interface and encapsulates its iteration state.

SubSequence

A type that represents a subsequence of some of the elements.

Import import Swift

Instance Variables

var array: [Self.Generator.Element] Required

Declaration

var array: [Self.Generator.Element] { get }
var elements: Self.Elements Required

A sequence containing the same elements as this one, possibly with a simpler type.

When implementing lazy operations, wrapping elements instead of self can prevent result types from growing an extra LazySequence layer. For example,

prext example neeeded

Note: this property need not be implemented by conforming types, it has a default implementation in a protocol extension that just returns self.

Declaration

var elements: Self.Elements { get }

Instance Methods

func dropFirst(_:)

Returns a subsequence containing all but the first n elements.

Requires: n >= 0 Complexity: O(n)

Declaration

func dropFirst(n: Int) -> Self.SubSequence

Declared In

SequenceType
func dropLast(_:)

Returns a subsequence containing all but the last n elements.

Requires: self is a finite sequence. Requires: n >= 0 Complexity: O(self.count)

Declaration

func dropLast(n: Int) -> Self.SubSequence

Declared In

SequenceType
func filter(_:)

Return an Array containing the elements of self, in order, that satisfy the predicate includeElement.

Declaration

func filter(@noescape includeElement: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.Generator.Element]

Declared In

SequenceType
func forEach(_:)

Call body on each element in self in the same order as a for-in loop.

sequence.forEach {
  // body code
}

is similar to:

for element in sequence {
  // body code
}

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

Complexity: O(self.count)

Declaration

func forEach(@noescape body: (Self.Generator.Element) throws -> ()) rethrows

Declared In

SequenceType
func generate() Required

Return a generator over the elements of this sequence.

Complexity: O(1).

Declaration

func generate() -> Self.Generator

Declared In

SequenceType
func map(_:)

Return an Array containing the results of mapping transform over self.

Complexity: O(N).

Declaration

func map<T>(@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]

Declared In

SequenceType
func prefix(_:)

Returns a subsequence, up to maxLength in length, containing the initial elements.

If maxLength exceeds self.count, the result contains all the elements of self.

Requires: maxLength >= 0

Declaration

func prefix(maxLength: Int) -> Self.SubSequence

Declared In

SequenceType
func split(_:allowEmptySlices:isSeparator:)

Returns the maximal SubSequences of self, in order, that don't contain elements satisfying the predicate isSeparator.

maxSplit: The maximum number of SubSequences to return, minus 1. If maxSplit + 1 SubSequences are returned, the last one is a suffix of self containing the remaining elements. The default value is Int.max.

allowEmptySubsequences: If true, an empty SubSequence is produced in the result for each pair of consecutive elements satisfying isSeparator. The default value is false.

Requires: maxSplit >= 0

Declaration

func split(maxSplit: Int, allowEmptySlices: Bool, @noescape isSeparator: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.SubSequence]

Declared In

SequenceType
func suffix(_:)

Returns a slice, up to maxLength in length, containing the final elements of s.

If maxLength exceeds s.count, the result contains all the elements of s.

Requires: self is a finite sequence. Requires: maxLength >= 0

Declaration

func suffix(maxLength: Int) -> Self.SubSequence

Declared In

SequenceType
func underestimateCount()

Return a value less than or equal to the number of elements in self, nondestructively.

Complexity: O(N).

Declaration

func underestimateCount() -> Int

Declared In

SequenceType

Default Implementations

var lazy: Self

Identical to self.

Declaration

var lazy: Self { get }
func contains(_:)

Return true iff an element in self satisfies predicate.

Declaration

func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool

Declared In

SequenceType
func dropFirst()

Returns a subsequence containing all but the first element.

Requires: n >= 0 Complexity: O(n)

Declaration

func dropFirst() -> Self.SubSequence

Declared In

SequenceType
func dropFirst(_:)

Returns a subsequence containing all but the first n elements.

Requires: n >= 0 Complexity: O(n)

Declaration

func dropFirst(n: Int) -> AnySequence<Self.Generator.Element>

Declared In

SequenceType
func dropLast()

Returns a subsequence containing all but the last element.

Requires: self is a finite sequence. Requires: n >= 0 Complexity: O(self.count)

Declaration

func dropLast() -> Self.SubSequence

Declared In

SequenceType
func dropLast(_:)

Returns a subsequence containing all but the last n elements.

Requires: self is a finite collection. Requires: n >= 0 Complexity: O(self.count)

Declaration

func dropLast(n: Int) -> AnySequence<Self.Generator.Element>

Declared In

SequenceType
func elementsEqual(_:isEquivalent:)

Return true iff self and other contain equivalent elements, using isEquivalent as the equivalence test.

Requires: isEquivalent is an equivalence relation.

Declaration

func elementsEqual<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence, @noescape isEquivalent: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Bool

Declared In

SequenceType
func enumerate()

Return a lazy SequenceType containing pairs (n, x), where ns are consecutive Ints starting at zero, and xs are the elements of base:

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

Declaration

func enumerate() -> EnumerateSequence<Self>

Declared In

SequenceType
func filter(_:)

Return the elements of self that satisfy predicate.

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

func filter(predicate: (Self.Elements.Generator.Element) -> Bool) -> LazyFilterSequence<Self.Elements>

Declared In

LazySequenceType, SequenceType
func flatMap<T>(_: (Self.Generator.Element) throws -> T?)

Return an Array containing the non-nil results of mapping transform over self.

Complexity: O(M + N), where M is the length of self and N is the length of the result.

Declaration

func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]

Declared In

SequenceType
func flatMap<S : SequenceType>(_: (Self.Generator.Element) throws -> S)

Return an Array containing the concatenated results of mapping transform over self.

s.flatMap(transform)

is equivalent to

Array(s.map(transform).flatten())

Complexity: O(M + N), where M is the length of self and N is the length of the result.

Declaration

func flatMap<S : SequenceType>(transform: (Self.Generator.Element) throws -> S) rethrows -> [S.Generator.Element]

Declared In

SequenceType
func flatMap(_:)

Returns the concatenated results of mapping transform over self. Equivalent to

self.map(transform).flatten()

Complexity: O(1)

Declaration

func flatMap<Intermediate : SequenceType>(transform: (Self.Elements.Generator.Element) -> Intermediate) -> LazySequence<FlattenSequence<LazyMapSequence<Self.Elements, Intermediate>>>
func forEach(_:)

Call body on each element in self in the same order as a for-in loop.

sequence.forEach {
  // body code
}

is similar to:

for element in sequence {
  // body code
}

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

Complexity: O(self.count)

Declaration

func forEach(@noescape body: (Self.Generator.Element) throws -> ()) rethrows

Declared In

SequenceType
func lexicographicalCompare(_:isOrderedBefore:)

Return true iff self precedes other in a lexicographical ("dictionary") ordering, using isOrderedBefore as the comparison between elements.

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, you should use String APIs that perform localized comparison.

Requires: isOrderedBefore is a strict weak ordering over the elements of self and other.

Declaration

func lexicographicalCompare<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence, @noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Bool

Declared In

SequenceType
func map(_:)

Return 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

func map<U>(transform: (Self.Elements.Generator.Element) -> U) -> LazyMapSequence<Self.Elements, U>

Declared In

LazySequenceType, SequenceType
func maxElement(_:)

Returns the maximum element in self or nil if the sequence is empty.

Complexity: O(elements.count).

Requires: isOrderedBefore is a strict weak ordering. over self.

Declaration

func maxElement(@noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element?

Declared In

SequenceType
func minElement(_:)

Returns the minimum element in self or nil if the sequence is empty.

Complexity: O(elements.count).

Requires: isOrderedBefore is a strict weak ordering. over self.

Declaration

func minElement(@noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element?

Declared In

SequenceType
func prefix(_:)

Returns a subsequence, up to maxLength in length, containing the initial elements.

If maxLength exceeds self.count, the result contains all the elements of self.

Requires: maxLength >= 0

Declaration

func prefix(maxLength: Int) -> AnySequence<Self.Generator.Element>

Declared In

SequenceType
func reduce(_:combine:)

Return the result of repeatedly calling combine with an accumulated value initialized to initial and each element of self, in turn, i.e. return combine(combine(...combine(combine(initial, self[0]), self[1]),...self[count-2]), self[count-1]).

Declaration

func reduce<T>(initial: T, @noescape combine: (T, Self.Generator.Element) throws -> T) rethrows -> T

Declared In

SequenceType
func reverse()

Return an Array containing the elements of self in reverse order.

Complexity: O(N), where N is the length of self.

Declaration

func reverse() -> [Self.Generator.Element]

Declared In

SequenceType
func sort(_:)

Return an Array containing the sorted elements of source according to isOrderedBefore.

The sorting algorithm is not stable (can change the relative order of elements for which isOrderedBefore does not establish an order).

Requires: isOrderedBefore is a strict weak ordering over the elements in self.

Declaration

func sort(@noescape isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) -> Bool) -> [Self.Generator.Element]

Declared In

SequenceType
func split(_:allowEmptySlices:isSeparator:)

Returns the maximal SubSequences of self, in order, that don't contain elements satisfying the predicate isSeparator.

maxSplit: The maximum number of SubSequences to return, minus 1. If maxSplit + 1 SubSequences are returned, the last one is a suffix of self containing the remaining elements. The default value is Int.max.

allowEmptySubsequences: If true, an empty SubSequence is produced in the result for each pair of consecutive elements satisfying isSeparator. The default value is false.

Requires: maxSplit >= 0

Declaration

func split(maxSplit: Int = default, allowEmptySlices: Bool = default, @noescape isSeparator: (Self.Generator.Element) throws -> Bool) rethrows -> [AnySequence<Self.Generator.Element>]

Declared In

SequenceType
func startsWith(_:isEquivalent:)

Return true iff self begins with elements equivalent to those of other, using isEquivalent as the equivalence test. Return true if other is empty.

Requires: isEquivalent is an equivalence relation.

Declaration

func startsWith<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence, @noescape isEquivalent: (Self.Generator.Element, Self.Generator.Element) throws -> Bool) rethrows -> Bool

Declared In

SequenceType
func suffix(_:)

Returns a slice, up to maxLength in length, containing the final elements of s.

If maxLength exceeds s.count, the result contains all the elements of s.

Requires: self is a finite sequence. Requires: maxLength >= 0

Declaration

func suffix(maxLength: Int) -> AnySequence<Self.Generator.Element>

Declared In

SequenceType
func underestimateCount()

Return a value less than or equal to the number of elements in self, nondestructively.

Complexity: O(N).

Declaration

func underestimateCount() -> Int

Declared In

SequenceType

Where Elements == Self

var elements: Self

Identical to self.

Declaration

var elements: Self { get }

Where Elements.Generator.Element == Generator.Element, Generator.Element : SequenceType

func flatten()

A concatenation of the elements of self.

Declaration

func flatten() -> LazySequence<FlattenSequence<Self.Elements>>

Where Generator == Self, Self : GeneratorType

func generate()

Return a generator over the elements of this sequence.

Complexity: O(1).

Declaration

func generate() -> Self

Declared In

SequenceType

Where Generator.Element : Comparable

func lexicographicalCompare(_:)

Return true iff self precedes other in a lexicographical ("dictionary") ordering, using "<" as the comparison between elements.

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, you should use String APIs that perform localized comparison.

Declaration

func lexicographicalCompare<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence) -> Bool

Declared In

SequenceType
func maxElement()

Returns the maximum element in self or nil if the sequence is empty.

Complexity: O(elements.count).

Declaration

func maxElement() -> Self.Generator.Element?

Declared In

SequenceType
func minElement()

Returns the minimum element in self or nil if the sequence is empty.

Complexity: O(elements.count).

Declaration

func minElement() -> Self.Generator.Element?

Declared In

SequenceType
func sort()

Return an Array containing the sorted elements of source.

The sorting algorithm is not stable (can change the relative order of elements that compare equal).

Requires: The less-than operator (func <) defined in the Comparable conformance is a strict weak ordering over the elements in self.

Declaration

func sort() -> [Self.Generator.Element]

Declared In

SequenceType

Where Generator.Element : Equatable

func contains(_:)

Return true iff element is in self.

Declaration

func contains(element: Self.Generator.Element) -> Bool

Declared In

SequenceType
func elementsEqual(_:)

Return true iff self and other contain the same elements in the same order.

Declaration

func elementsEqual<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence) -> Bool

Declared In

SequenceType
func split(_:maxSplit:allowEmptySlices:)

Returns the maximal SubSequences of self, in order, around elements equatable to separator.

maxSplit: The maximum number of SubSequences to return, minus 1. If maxSplit + 1 SubSequences are returned, the last one is a suffix of self containing the remaining elements. The default value is Int.max.

allowEmptySubsequences: If true, an empty SubSequence is produced in the result for each pair of consecutive elements satisfying isSeparator. The default value is false.

Requires: maxSplit >= 0

Declaration

func split(separator: Self.Generator.Element, maxSplit: Int = default, allowEmptySlices: Bool = default) -> [AnySequence<Self.Generator.Element>]

Declared In

SequenceType
func startsWith(_:)

Return true iff the the initial elements of self are equal to prefix. Return true if other is empty.

Declaration

func startsWith<OtherSequence : SequenceType where OtherSequence.Generator.Element == Generator.Element>(other: OtherSequence) -> Bool

Declared In

SequenceType

Where Generator.Element : SequenceType

func flatten()

A concatenation of the elements of self.

Declaration

func flatten() -> FlattenSequence<Self>

Declared In

SequenceType
func joinWithSeparator(_:)

Returns a view, whose elements are the result of interposing a given separator between the elements of the sequence self.

For example, [[1, 2, 3], [4, 5, 6], [7, 8, 9]].joinWithSeparator([-1, -2]) yields [1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9].

Declaration

func joinWithSeparator<Separator : SequenceType where Separator.Generator.Element == Generator.Element.Generator.Element>(separator: Separator) -> JoinSequence<Self>

Declared In

SequenceType

Where Generator.Element == String

func joinWithSeparator(_:)

Interpose the separator between elements of self, then concatenate the result. For example:

["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"

Declaration

func joinWithSeparator(separator: String) -> String

Declared In

SequenceType