Add “for in” support to iterate over Swift custom classes

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

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.

More info: http://lillylabs.no/2014/09/30/make-iterable-swift-collection-type-sequencetype

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)