swift 中很好用的for循环语句for...in.它的实现原理是需要遵循SequenceType,且要县遵循GenreatorType 先看下面例子
//先定义一个实现了 GenreatorType Protocol的类型
`class TestList: SequenceType {
private var testList:[Test]?
init() {
self.testList = [Test]()
}
func addTest(test:test){
self.testList?.append(book)
}
typealias Generator = BookListGenerator
func generate() -> Generator {
return testListGenerator(bookList: self.bookList!)
}
}`
class test {
var name:String = ""
init(name: String) {
self.name = name
}
}
class TestListGenerator : GeneratorType {}
typealias Element = Book
var currentIndex:Int = 0
var testList:[Test]?
init(testList: [Test]) {
self.testList = bookList
}
func next() -> Element? {
guard let list = testList else { return nil }
if currentIndex < list.count {
let element = list[currentIndex]
currentIndex += 1
return element
}else {
return nil
}
}
}
let testList = testList()
testList.addTest(Test(name: "Swift"))
testList.addTest(Test(name: "iOS" ))
for test in testList {
print("\(test.name)")
}
- 看了上述的例子,大致可以自定义一个可以for...in的对象了
- 更惊喜的是我不还可以使用想数组的map\filter、reduce方法,这因为SquenceType已经扩展实现了它们