Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 'for...in' support to a class in Swift 2

Tags:

ios

swift

swift2

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?

like image 946
markdb314 Avatar asked Feb 09 '23 10:02

markdb314


1 Answers

There are just two changes:

  • GeneratorOf is now called AnyGenerator.

  • GeneratorOf.init(next:) is now a function anyGenerator()

That gives us:

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

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

like image 149
Rob Napier Avatar answered Feb 19 '23 00:02

Rob Napier