添加“for in"支持迭代 Swift 自定义类 [英] Add "for in" support to iterate over Swift custom classes

查看:35
本文介绍了添加“for in"支持迭代 Swift 自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,我们可以使用 for..in 循环遍历 ArraysDictionaries.但是,我想像这样迭代我自己的 CustomClass:

As we know, we can use the for..in loop to iterate across Arrays or Dictionaries. However, I would like to iterate over my own CustomClass like this:

for i in CustomClass {
    someFunction(i)
}

CustomClass 必须支持哪些操作/协议才能实现这一点?

What operations/protocols does CustomClass have to support for this to be possible?

推荐答案

假设您有一个类Cars",您希望能够使用 for..in 循环进行迭代:

Say you have a class "Cars" that you want to be able to iterate over using a for..in loop:

let cars = Cars()

for car in cars {
    println(car.name)
}

最简单的方法是将 AnyGenerator 与这样的类一起使用:

The simplest way is to use AnyGenerator with the classes like this:

class Car {
    var name : String
    init(name : String) {
        self.name = name
    }
}

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 AnyGenerator<Car> instance, passing a closure that returns the next car in the iteration
        return anyGenerator {
            if (nextIndex < 0) {
                return nil
            }
            return self.carList[nextIndex--]
        }
    }
}

要尝试一个完整的工作示例,请添加上面的两个类,然后尝试像这样使用它们,添加几个测试项:

To try a complete working sample add the two classes above and then try to use them like this, adding a couple of test items:

    let cars = Cars()

    cars.carList.append(Car(name: "Honda"))
    cars.carList.append(Car(name: "Toyota"))

    for car in cars {
        println(car.name)
    }


就是这样,很简单.


That's it, simple.

更多信息:http://lillylabs.no/2014/09/30/make-iterable-swift-collection-type-sequencetype

这篇关于添加“for in"支持迭代 Swift 自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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