这个问题 https://stackoverflow.com/questions/24099227/add-for-in-support-to-iterate-over-swift-custom-classes早期版本的 Swift 已经得到了答案,但我想知道如何向 Swift 2 中的类添加“for...in”支持。看来新版本的 Swift 中发生了足够的变化,使答案显着不同的。例如,看起来您现在应该使用 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 语法。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)