这是运行良好的代码,这是迭代器模式的实现:
struct Candies {
let candies: [String]
}
extension Candies: Sequence {
func makeIterator() -> CandiesIterator {
return CandiesIterator(sequence: candies, current: 0)
}
}
struct CandiesIterator: IteratorProtocol {
let sequence: [String]
var current = 0
mutating func next() -> String? {
defer { current += 1 }
return sequence.count > current ? sequence[current] : nil
}
}
这是我认为是上述代码的通用变体的代码,但我有两个错误(请参见下面的代码):
struct Whatevers<T> {
let whatevers: [T]
}
extension Whatevers: Sequence {
func makeIterator() -> Whatevers<T>.Iterator {
return WhateversIterator(sequence: whatevers, current: 0)
}
}
struct WhateversIterator<T>: IteratorProtocol {
let sequence: [T]
var current = 0
mutating func next() -> WhateversIterator.Element? {
defer { current += 1 }
return sequence.count > current ? sequence[current] : nil
}
}
error: MyPlayground.playground:854:1: error: type 'Whatevers' does not conform to protocol 'Sequence' extension Whatevers: Sequence { ^
error: MyPlayground.playground:861:8: error: type 'WhateversIterator' does not conform to protocol 'IteratorProtocol' struct WhateversIterator: IteratorProtocol {
有人可以解释一下这段代码中有什么不正确的地方吗?我怎样才能让它发挥作用?
最佳答案
找到解决方案!
struct Whatevers<T> {
let whatevers: [T]
}
extension Whatevers: Sequence {
func makeIterator() -> WhateversIterator<T> {
return WhateversIterator(sequence: whatevers, current: 0)
}
}
struct WhateversIterator<T>: IteratorProtocol {
let sequence: [T]
var current = 0
mutating func next() -> T? {
defer { current += 1 }
return sequence.count > current ? sequence[current] : nil
}
}
所有错误都与从函数 makeIterator 和 next 返回类型有关。
希望有人会觉得它有帮助!
关于swift - 尝试从工作迭代器模式中获取通用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45768880/