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


Swift Sequence用法及代碼示例

協議

Sequence

一種提供對其元素的順序、迭代訪問的類型。

聲明

protocol Sequence<Element>

概述

序列是一個值列表,您可以一次通過一個值。迭代序列元素的最常見方法是使用 for - in 循環:


let oneTwoThree = 1...3
for number in oneTwoThree {
    print(number)
}
// Prints "1"
// Prints "2"
// Prints "3"

雖然看似簡單,但此函數使您可以訪問可以在任何序列上執行的大量操作。例如,要檢查序列是否包含特定值,您可以按順序測試每個值,直到找到匹配項或到達序列末尾。此示例檢查特定昆蟲是否在數組中。


let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
var hasMosquito = false
for bug in bugs {
    if bug == "Mosquito" {
        hasMosquito = true
        break
    }
}
print("'bugs' has a mosquito: \(hasMosquito)")
// Prints "'bugs' has a mosquito: false"

Sequence 協議為依賴順序訪問序列值的許多常見操作提供默認實現。為了更清晰、更簡潔的代碼,上麵的示例可以使用數組的 contains(_:) 方法,每個序列都繼承自 Sequence ,而不是手動迭代:


if bugs.contains("Mosquito") {
    print("Break out the bug spray.")
} else {
    print("Whew, no mosquitos!")
}
// Prints "Whew, no mosquitos!"

重複訪問

Sequence 協議對一致性類型沒有關於它們是否會被迭代破壞性消耗的要求。因此,不要假設序列上的多個 for - in 循環或者恢複迭代,或者從頭開始:


for element in sequence {
    if ... some condition { break }
}


for element in sequence {
    // No defined behavior
}

在這種情況下,您不能假設一個序列是可消耗的並且將恢複迭代,或者一個序列是一個集合並將從第一個元素重新開始迭代。在第二個for - in 循環中,允許非集合的符合序列產生任意元素序列。

要確定您創建的類型支持非破壞性迭代,請添加對Collection 協議的一致性。

符合序列協議

使您自己的自定義類型符合Sequence 可以輕鬆實現許多有用的操作,例如for - in 循環和contains 方法。要將Sequence 一致性添加到您自己的自定義類型,請添加一個返回迭代器的makeIterator() 方法。

或者,如果您的類型可以充當自己的迭代器,那麽實現IteratorProtocol 協議的要求並聲明符合SequenceIteratorProtocol 就足夠了。

下麵是一個 Countdown 序列的定義,該序列用作它自己的迭代器。 makeIterator() 方法作為默認實現提供。


struct Countdown: Sequence, IteratorProtocol {
    var count: Int


    mutating func next() -> Int? {
        if count == 0 {
            return nil
        } else {
            defer { count -= 1 }
            return count
        }
    }
}


let threeToGo = Countdown(count: 3)
for i in threeToGo {
    print(i)
}
// Prints "3"
// Prints "2"
// Prints "1"

預期表現

一個序列應該在 O(1) 中提供它的迭代器。 Sequence 協議對元素訪問沒有其他要求,因此除非另有說明,否則應將遍曆序列的例程視為 O(n)。

可用版本

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

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Sequence。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。