当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift sequence(first:next:)用法及代码示例


函数

sequence(first:next:)

返回由 first 和重复的 next 的惰性应用程序形成的序列。

声明

func sequence<T>(
    first: T,
    next: @escaping (T) -> T?
) -> UnfoldFirstSequence<T>

返回值

一个以 first 开头并通过将前一个元素传递给 next 来继续返回的每个值的序列。

参数

first

要从序列中返回的第一个元素。

next

接受前一个序列元素并返回下一个元素的闭包。

详述

序列中的第一个元素始终是 first ,每个后续元素都是使用前一个元素调用 next 的结果。当 next 返回 nil 时,序列结束。如果 next 从不返回 nil ,则序列是无限的。

此函数可用于替换以前使用 C-style for 循环处理的许多情况。

例子:


// Walk the elements of a tree from a node up to the root
for node in sequence(first: leaf, next: { $0.parent }) {
  // node is leaf, then leaf.parent, then leaf.parent.parent, etc.
}


// Iterate over all powers of two (ignoring overflow)
for value in sequence(first: 1, next: { $0 * 2 }) {
  // value is 1, then 2, then 4, then 8, etc.
}

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 sequence(first:next:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。