ios swift 进阶 - 基础原理探索 合集- 荔枝
Sequence 说明
Sequence作为swift集合类协议扩展方法,为集合提供了一系列的序列迭代能力。
for in 本质
Sequence是通过Iterator来访问元素的。Iterator是一个迭代器,我们来看一段代码,如下:
let nums = [1, 2, 3, 4, 5];
for element in nums {
print(element)
}
- 在
Swift中的for in其实是一个语法糖,那么它的本质是什么呢?
1.其实是 调用了Sequence.makeIterator方法,创建一个Iterator,把数组传给迭代器。
2.调用IteratorProtocol.next方法,将数组元素遍历出来。
Sequence 核心代码定义
public protocol Sequence<Element> {
/// A type representing the sequence's elements.
associatedtype Element where Self.Element == Self.Iterator.Element
/// A type that provides the sequence's iteration interface and
/// encapsulates its iteration state.
associatedtype Iterator : IteratorProtocol
}
- 在该协议中,最重要的就是创建了一个迭代器
-
- 查看一下
IteratorProtocol定义
- 查看一下
public protocol IteratorProtocol {
/// The type of element traversed by the iterator.
associatedtype Element
mutating func next() -> Self.Element?
}
- 它有一个
next方法,可以通过调用next方法来返回元素。 - 所以我们每次在使用 for..in 的时候,其实都是 通过sequence创建一个迭代器,用这个集合的迭代器来遍历当前集合或者序列当中的元素
自己定义一个遵循Sequence的结构体
struct LGSequence: Sequence {
// 指定Element类型为Int
typealias Element = Int
var arrayCount: Int
init(_ count: Int) {
self.arrayCount = count
}
// 为Sequence创建一个迭代器,来遍历Seq中的元素
func makeIterator() -> LGIterator{
return LGIterator(self)
}
}
/// 迭代器,遵循 IteratorProtocol 协议
struct LGIterator: IteratorProtocol {
// 指定Element类型为Int
typealias Element = Int
let seq: LGSequence
var count = 0
// 提供一个构造方法,方便初始化迭代器
init(_ sequence: LGSequence) {
self.seq = sequence
}
// next 方法以count作为自增的操作
mutating func next() -> Int? {
guard count < self.seq.arrayCount else {
return nil
}
count += 1
return count
}
}
let seq = LGSequence.init(10)
for element in seq {
print(element)
}
// 打印结果
//1
//2
//3
//4
//5
//6
//7
//8
//9
//10