I want to implement a custom iterable class that can contain nil elements, similar to [Any?]
. Conforming to SequenceType mostly works except the contract of GeneratorType.next()
says it should return nil when all elements have been exhausted. Is there a workaround?
Here is a (quite silly) example:
struct OddSequence : SequenceType {
func generate() -> GeneratorOf<Int?> {
var current = 0
return GeneratorOf<Int?>() {
if current >= 6 {
return nil
}
current++
if current % 2 == 0 {
return current
} else {
return Optional(nil)
}
}
}
}
for x in OddSequence() {
println(x)
}
Output:
nil
Optional(2)
nil
Optional(4)
nil
Optional(6)
The generator returns an optional (which can be Optional(nil)
) for each element,
and nil
if the sequence is exhausted.
See also "Optionals Case Study: valuesForKeys" in the Swift blog about the difference between nil
and
Optional(nil)
and its applications.
Update for Swift 2:
struct OddSequence : SequenceType {
func generate() -> AnyGenerator<Int?> {
var current = 0
return anyGenerator {
if current >= 6 {
return nil
}
current++
if current % 2 == 0 {
return current
} else {
return Optional(nil)
}
}
}
}
for x in OddSequence() {
print(x)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With