在Swift 2中为类添加'for ... in'支持 [英] Add 'for...in' support to a class in Swift 2

查看:144
本文介绍了在Swift 2中为类添加'for ... in'支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题已经存在回答了早期版本的Swift,但是我想知道如何在Swift 2中为类添加"for ... in"支持.看来,新版本的Swift中已经发生了足够的变化以使答案有很大不同.例如,看来您现在应该使用AnyGenerator协议?

This question has already been answered for earlier versions of Swift, but I'm wondering how to add 'for...in' support to a class in Swift 2. It appears that enough has changed in the new version of Swift to make the answer significantly different. For example, it appears that you should be using the AnyGenerator protocol now?

推荐答案

只有两个更改:

  • 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语法.)

(I've edited the linked answer to match Swift 2 syntax.)

这篇关于在Swift 2中为类添加'for ... in'支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆