結構
Indexing
IndexingIterator
一種使用其索引迭代集合的類型。
聲明
@frozen struct IndexingIterator<Elements> where Elements : Collection
概述
IndexingIterator
類型是任何未聲明自己的集合的默認迭代器。它通過使用集合的索引來遍曆集合中的每個值,從而充當迭代器。標準庫中的大多數集合都使用IndexingIterator
作為它們的迭代器。
默認情況下,您創建的任何自定義集合類型都將繼承一個返回 IndexingIterator
實例的 makeIterator()
方法,因此無需聲明您自己的。創建自定義集合類型時,添加Collection
協議的最低要求:開始和結束索引以及訪問元素的下標。定義了這些元素後,繼承的makeIterator()
方法滿足Sequence
協議的要求。
這是一個聲明集合的最低要求的類型示例。 CollectionOfTwo
結構是一個固定大小的集合,它始終包含兩個特定類型的元素。
struct CollectionOfTwo<Element>: Collection {
let elements: (Element, Element)
init(_ first: Element, _ second: Element) {
self.elements = (first, second)
}
var startIndex: Int { return 0 }
var endIndex: Int { return 2 }
subscript(index: Int) -> Element {
switch index {
case 0: return elements.0
case 1: return elements.1
default: fatalError("Index out of bounds.")
}
}
func index(after i: Int) -> Int {
precondition(i < endIndex, "Can't advance beyond endIndex")
return i + 1
}
}
因為 CollectionOfTwo
沒有定義自己的 makeIterator()
方法或 Iterator
關聯類型,所以它使用默認迭代器類型 IndexingIterator
。這個例子展示了如何創建一個 CollectionOfTwo
實例來保存一個點的值,然後使用 for
- in
循環進行迭代。
let point = CollectionOfTwo(15.0, 20.0)
for element in point {
print(element)
}
// Prints "15.0"
// Prints "20.0"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift IndexingIterator shuffled()用法及代碼示例
- Swift IndexingIterator prefix(_:)用法及代碼示例
- Swift IndexingIterator elementsEqual(_:)用法及代碼示例
- Swift IndexingIterator dropLast(_:)用法及代碼示例
- Swift IndexingIterator joined(separator:)用法及代碼示例
- Swift IndexingIterator filter(_:)用法及代碼示例
- Swift IndexingIterator prefix(while:)用法及代碼示例
- Swift IndexingIterator split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift IndexingIterator contains(_:)用法及代碼示例
- Swift IndexingIterator flatMap(_:)用法及代碼示例
- Swift IndexingIterator allSatisfy(_:)用法及代碼示例
- Swift IndexingIterator lexicographicallyPrecedes(_:)用法及代碼示例
- Swift IndexingIterator sorted()用法及代碼示例
- Swift IndexingIterator shuffled(using:)用法及代碼示例
- Swift IndexingIterator suffix(_:)用法及代碼示例
- Swift IndexingIterator enumerated()用法及代碼示例
- Swift IndexingIterator max(by:)用法及代碼示例
- Swift IndexingIterator contains(where:)用法及代碼示例
- Swift IndexingIterator min()用法及代碼示例
- Swift IndexingIterator max()用法及代碼示例
- Swift IndexingIterator reduce(_:_:)用法及代碼示例
- Swift IndexingIterator min(by:)用法及代碼示例
- Swift IndexingIterator dropFirst(_:)用法及代碼示例
- Swift IndexingIterator sorted(by:)用法及代碼示例
- Swift IndexingIterator starts(with:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 IndexingIterator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。