Returns a sequence formed from repeated lazy applications of next
to a
mutable state
.
The elements of the sequence are obtained by invoking next
with a mutable
state. The same state is passed to all invocations of next
, so subsequent
calls will see any mutations made by previous calls. The sequence ends when
next
returns nil
. If next
never returns nil
, the sequence is
infinite.
This function can be used to replace many instances of AnyIterator
that
wrap a closure.
Example:
// Interleave two sequences that yield the same element type
sequence
(
state
: (
false
,
seq1
.
makeIterator
(),
seq2
.
makeIterator
()),
next
: {
iters
in
iters
.
0
= !
iters
.
0
return
iters
.
0
?
iters
.
1
.
next
() :
iters
.
2
.
next
()
})
state
: The initial state that will be passed to the closure.
next
: A closure that accepts an inout
state and returns the
next element of the sequence.
Returns: A sequence that yields each successive value from next
.
See Also: sequence(first:next:)
Declaration
func
sequence
<
T
,
State
>
(
state
:
State
,
next
: @
escaping
(
inout
State
) -
>
T
?) -
>
UnfoldSequence
<
T
,
State
>
Returns a sequence formed from
first
and repeated lazy applications ofnext
.The first element in the sequence is always
first
, and each successive element is the result of invokingnext
with the previous element. The sequence ends whennext
returnsnil
. Ifnext
never returnsnil
, the sequence is infinite.This function can be used to replace many cases that were previously handled using C-style
for
loops.Example:
first
: The first element to be returned from the sequence.next
: A closure that accepts the previous sequence element and returns the next element. Returns: A sequence that starts withfirst
and continues with every value returned by passing the previous element tonext
.See Also:
sequence(state:next:)
Declaration
func
sequence
<
T
>
(
first
:
T
,
next
: @
escaping
(
T
) -
>
T
?) -
>
UnfoldSequence
<
T
, (
T
?,
Bool
)
>