一尘不染

添加“ for in”支持以遍历Swift定制类

swift

众所周知,我们可以使用for..in循环遍历ArraysDictionaries。但是,我想这样迭代自己CustomClass

for i in CustomClass {
    someFunction(i)
}

CustomClass为了使之成为可能,必须支持哪些操作/协议?


阅读 240

收藏
2020-07-07

共1个答案

一尘不染

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

let cars = Cars()

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

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

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--]
        }
    }
}

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

    let cars = Cars()

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

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

就是这样,很简单。

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

2020-07-07