Last active
December 12, 2018 01:52
-
-
Save 13hoop/477e5804c59a10e193101267e266bb29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//-------- swift 集合类型解读 - 1210 | |
/* | |
--> Sequence 协议 | |
这个协议是内置集合类型的核心,正是它让 针对元素序列的通用操作 成为可能 | |
其规定了要实现跟返回一个 迭代器(Iterator) | |
protocol Sequence { | |
associatedtype Iterator: IteratorProtocol // 这里使用了 关联类型,作用就是协议中的 “范型” 或者 “alias” | |
func makeIterator() -> Iterator | |
} | |
--> IteratorProtocol 协议,一般只有在自定义序列类型的时候才使用 | |
protocol IteratorProtocol { | |
associatedtype Element | |
mutating func next() -> Element? | |
} | |
for element in someSequence { | |
doSomething(with: element) | |
} | |
实际上就是,我想试用过FMDB的对此不会陌生: | |
var iterator = someSequence.makeIterator() | |
while let element = iterator.next() { | |
doSomething(with: element) | |
} | |
*/ | |
// 一个更加有意义的例子,模拟一个 Fibslterator | |
struct Filbslterator: IteratorProtocol { | |
var state = (0, 1) | |
typealias Element = Int | |
mutating func next() -> Element? { | |
let upcomingNumber = state.0 | |
state = (state.1, state.0 + state.1) | |
return upcomingNumber | |
} | |
} | |
var iterator = Filbslterator() | |
while let x = iterator.next() { | |
if(x > 100) { | |
break | |
} | |
print(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment