當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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