ios - 向 Swift 2 中的类添加 'for...in' 支持

标签 ios swift swift2

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/

相关文章:

json - swift 2中NSJSONSerialization的线程中断1.1

ios - 我在 swift2 中使用 objective-c 类,如何实现委托(delegate)方法并绑定(bind)该委托(delegate)

iOS swift : Filter array to unique items

ios - 当新的 iOS 应用程序安装 iphone 时收到通知

arrays - 使用 Swift 反转数组中的字符串

ios - 使用委托(delegate)模式的选择器无效

ios - 可以从与上止点不同的起始角度绘制 iOS 图表中的饼图吗?

ios - 使用 Restkit 映射养蜂场

ios - 如何使用 swift 为多注释设置数组

ios - 如何在 IOS Swift OpenglES 1.0/1.1/2.0 上将文本和图像绘制为纹理