Sequence/Collection 层次结构
了解 Sequence 与 Collection (以及 Bidirectional/RandomAccess)的区别:遍历保证、索引,以及算法何时需要更强的协议。
Sequence/Collection 层次结构 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 1 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 3 节课。
层级图
可迭代类型层级:
- 序列:通过迭代器进行迭代(可能只能单遍迭代)。
- 集合:支持多遍迭代,并且可通过索引访问(startIndex/endIndex)。
- BidirectionalCollection:可以向后移动索引。
- RandomAccessCollection:支持常数时间的索引步进。
序列迭代
序列保证您可以按顺序迭代元素;但不要求提供索引或支持多遍迭代。
let seq = [1, 2, 3] as AnySequence<Int> // wrap as AnySequence for demo
for x in seq { print(x, terminator: " ") }
print("")集合索引
集合增加了索引,并允许进行多遍遍历。您可以安全地重新迭代。
let arr = ["a","b","c"] // Array is a Collection
print(arr.startIndex == 0) // true for Array
print(arr.endIndex == 3) // endIndex is "one past last"
for i in arr.indices { print(arr[i], terminator: " ") }
print("")
// Iterate again (multi-pass)
for ch in arr { print(ch, terminator: " ") }
print("")更强的能力
BidirectionalCollection可以向后移动索引。RandomAccessCollection支持常数时间的索引步进(例如数组)。
let text = "Swift" // String is a BidirectionalCollection
var i = text.index(before: text.endIndex) // move backward
print(text[i]) // last character
// Array is RandomAccessCollection: jumping indices is cheap
let nums = [10,20,30,40]
print(nums[nums.startIndex.advanced(by: 2)]) // 30自定义序列
自定义序列可能只能进行单遍迭代。迭代一次后,迭代器可能已经耗尽。
struct Countdown: Sequence, IteratorProtocol {
var current: Int
mutating func next() -> Int? {
guard current >= 0 else { return nil }
defer { current -= 1 }
return current
}
}
var cd = Countdown(current: 3)
for n in cd { print(n, terminator: " ") } // 3 2 1 0
print("")
// cd is exhausted; iterating again yields nothing (single-pass behavior)选择合适的协议
指导原则:
- 当一次遍历就足够时,在序列上使用泛型算法。
- 需要多遍遍历或索引操作时,要求使用集合。
- 对于经常跳转索引的算法(例如二分查找),优先使用RandomAccessCollection。
集合与序列
快速检查:集合相较于序列增加了什么?
回顾
回顾:序列 → 基本迭代。集合 → 索引 + 多遍迭代。BidirectionalCollection → 向后移动。RandomAccessCollection → 常数时间的索引步进。请选择符合算法需求的最小协议。
用 AI 导师学习 Swift — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 122
- 课程
- 409
常见问题解答
「Sequence/Collection 层次结构」课时是免费的吗?
是的 — 「Sequence/Collection 层次结构」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 3 节课。
「Sequence/Collection 层次结构」这节课中我会学到什么?
了解 Sequence 与 Collection (以及 Bidirectional/RandomAccess)的区别:遍历保证、索引,以及算法何时需要更强的协议。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 3 节。
「Sequence/Collection 层次结构」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Sequence/Collection 层次结构
- Map/Filter/Reduce 与惰性序列
- 自定义迭代器与性能技巧