在Swift 2中为一个类添加'for ... in'支持

mar*_*314 4 ios swift swift2

对于早期版本的Swift,这个问题已经得到了解答,但是我想知道如何在Swift 2的类中添加"for ... in"支持.看起来在新版本的Swift中已经有了足够的变化来制作答案明显不同.例如,您现在应该使用AnyGenerator协议?

Rob*_*ier 8

只有两个变化:

  • 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--]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(我编辑了链接的答案以匹配Swift 2语法.)