gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:48:48 24 4
gpt4 key购买 nike

我想实现一个可以包含 nil 元素的自定义可迭代类,类似于 [Any?]。除了 GeneratorType.next() 的契约规定它应该在所有元素都已用尽时返回 nil 之外,符合 SequenceType 大部分情况下是有效的。有解决方法吗?

最佳答案

这是一个(非常愚蠢的)例子:

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)),如果序列已用完,则为 nil

另见 "Optionals Case Study: valuesForKeys"在 Swift 博客中关于 nilOptional(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)
}

关于swift - 是否可以实现包含 nil 元素的 Swift SequenceType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com