函數
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:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。