是否可以实现包含nil元素的Swift SequenceType?

前端之家收集整理的这篇文章主要介绍了是否可以实现包含nil元素的Swift SequenceType?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想实现一个可以包含nil元素的自定义可迭代类,类似于[Any?].符合SequenceType主要是有效的,除了GeneratorType.next()的契约,它表示当所有元素都用尽时它应该返回nil.有解决方法吗?
这是一个(非常愚蠢)的例子:
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)
}

输出

nil
Optional(2)
nil
Optional(4)
nil
Optional(6)

生成器为每个元素返回一个可选的(可以是Optional(nil)),
如果序列耗尽则为零.

另请参阅Swift博客中的“Optionals Case Study: valuesForKeys”,了解nil和.之间的区别
可选(零)及其应用程序.

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)
}
原文链接:https://www.f2er.com/swift/319496.html

猜你在找的Swift相关文章