This question已经回答了早期版本的 Swift,但我想知道如何为 Swift 2 中的类添加“for...in”支持。看来新版本的 Swift 中已经发生了足够多的变化,足以使答案显着不同的。例如,您现在似乎应该使用 AnyGenerator 协议(protocol)?
最佳答案
只有两个变化:
GeneratorOf
现在称为AnyGenerator
。GeneratorOf.init(next:)
现在是一个函数anyGenerator()
这给了我们:
class Cars : SequenceType {
var carList : [Car] = []
func generate() -> AnyGenerator<Car> {
// keep the index of the next car in the iteration
var nextIndex = carList.count-1
// Construct a GeneratorOf<Car> instance, passing a closure that returns the next car in the iteration
return anyGenerator {
if (nextIndex < 0) {
return nil
}
return self.carList[nextIndex--]
}
}
}
(我已经编辑了链接的答案以匹配 Swift 2 语法。)
关于ios - 向 Swift 2 中的类添加 'for...in' 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730127/