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?
Asked
Active
Viewed 451 times
4
-
1[This answer](http://stackoverflow.com/a/31074933/2227743) in the page you've linked seems to address the problem. – Eric Aya Jul 30 '15 at 17:22
-
It does not answer my question. That code doesn't even compile in Swift 2 – markdb314 Jul 30 '15 at 17:27
-
Show your code, what did you try? What exactly doesn't work? – zrzka Jul 30 '15 at 17:28
-
I'm just looking for an extremely simple example, adding my code would just confuse matters, because I don't know what I'm doing. I think I'm having trouble because I don't fully understand how protocol extensions affect this in Swift 2 – markdb314 Jul 30 '15 at 17:31
2 Answers
8
There are just two changes:
GeneratorOf
is now calledAnyGenerator
.GeneratorOf.init(next:)
is now a functionanyGenerator()
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.)

Rob Napier
- 286,113
- 34
- 456
- 610
-
-
-
Needs update for Swift 2.2 http://stackoverflow.com/questions/36512156/using-anygenerator-with-swift-2-2-for-in-loop-support-for-custom-classes – Suragch Apr 09 '16 at 02:57
0
This comes straight from one of the comments on an answer to that question...
Now that we have protocol extensions in Swift 2.0, this works a bit differently. Instead of conforming to SequenceType, one should simply subclass AnyGenerator and override the next() method to return the proper item in the iteration (in this case, next() –> Car?)

pbush25
- 5,228
- 2
- 26
- 35
-
Yes, I saw that, but I would like a complete example... I tried implementing it, and it wasn't as straightforward as it sounds – markdb314 Jul 30 '15 at 17:25
-
Well could you please add your code to your question showing what you tried? – pbush25 Jul 30 '15 at 17:26
-
I don't understand why this comment was made. `SequenceType` is still the protocol for `for...in`. There's no need to subclass `AnyGenerator` for simple usages like this (though it's legal if you want to). – Rob Napier Jul 30 '15 at 17:35