函数
sequence(first:
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+
相关用法
- Swift sequence(state:next:)用法及代码示例
- Swift stride(from:through:by:)用法及代码示例
- Swift stride(from:to:by:)用法及代码示例
- Swift KeyValuePairs flatMap(_:)用法及代码示例
- Swift String.UTF8View first用法及代码示例
- Swift Result.Publisher zip(_:_:_:)用法及代码示例
- Swift Optional.Publisher reduce(_:_:)用法及代码示例
- Swift Int8 ~(_:)用法及代码示例
- Swift SetAlgebra isStrictSubset(of:)用法及代码示例
- Swift UInt +(_:)用法及代码示例
- Swift Array enumerated()用法及代码示例
- Swift FlattenSequence prefix(_:)用法及代码示例
- Swift Slice endIndex用法及代码示例
- Swift LazySequence split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代码示例
- Swift MutableCollection partition(by:)用法及代码示例
- Swift ReversedCollection min(by:)用法及代码示例
- Swift RandomNumberGenerator用法及代码示例
- Swift Dictionary.Keys shuffled()用法及代码示例
- Swift AnySequence elementsEqual(_:)用法及代码示例
- Swift UInt &<<(_:_:)用法及代码示例
- Swift Optional.Publisher tryDrop(while:)用法及代码示例
- Swift DefaultIndices endIndex用法及代码示例
- Swift Substring.UnicodeScalarView insert(contentsOf:at:)用法及代码示例
- Swift LazyFilterSequence dropFirst(_:)用法及代码示例
- Swift LazySequence suffix(from:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 sequence(first:next:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。