试图从工作Iterator模式中获取通用代码

时间:2017-08-19 07:23:31

标签: swift generics design-patterns iterator

这是可以正常工作的代码,这是Iterator模式的实现:

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
    }
}
  

错误:MyPlayground.playground:854:1:错误:输入'Whatevers'   不符合协议'序列'扩展Whatevers:Sequence {^

     

错误:MyPlayground.playground:861:8:错误:输入   'WhateversIterator'不符合协议'IteratorProtocol'   struct WhateversIterator:IteratorProtocol {

有人可以解释此代码中的错误。我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:2)

找到解决方案!

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 返回类型。

希望有人会发现它有用!