Implement enum / collection class in Swift
I am trying to implement a class (implements SequenceType) and it seems a little more complicated than I expected. In C #, I just need to implement IEnumerable
and " yield return
", which makes it pretty simple. It's the same in python with __iter__()
and with yield
. But in Swift, I don't know why it's too difficult. Here is the code
class Nums : SequenceType{
let list = [1,2,3,4,5]
func generate() -> GeneratorOf<Int?> {
return GeneratorOf<Int?>{
for i in self.list{
return i
}
return nil
}
}
}
When I call it in for-in
, it goes into an infinite loop.
What's the correct way to implement repeating classes in swift?
source to share
return
inside a generator does not work like yield
in C #, Python and other languages. This is just a simple instruction return
.
Instead, Swift generators use optional vaules - Some(x)
indicates the next item in the sequence, and None
/ or nil
signals the end of the sequence.
The block you pass to the constructor GeneratorOf<Int>
(by the way, you don't need to use it Int?
) will be called at every step and must call the next value every time it is called, or nil
when it is done. This way you can use a mutable variable to track the state:
func generate() -> GeneratorOf<Int>
{
var i = 0
return GeneratorOf<Int> {
if i >= self.list.count { return nil }
return self.list[i++]
}
}
Or you can even use the built-in generator list
:
func generate() -> GeneratorOf<Int>
{
var g = self.list.generate()
return GeneratorOf<Int> {
return g.next() // not very exciting... we might as well have returned g itself
}
}
source to share