Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement a Swift SequenceType that contains nil elements?

Tags:

swift

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?

like image 285
ide Avatar asked Sep 11 '14 18:09

ide


1 Answers

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)
}
like image 102
Martin R Avatar answered Oct 23 '22 04:10

Martin R