swift - 尝试从工作迭代器模式中获取通用代码

标签 swift generics design-patterns 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
    }
}

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

所有错误都与从函数 ma​​keIteratornext 返回类型有关。

希望有人会觉得它有帮助!

关于swift - 尝试从工作迭代器模式中获取通用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45768880/

相关文章:

Android List<T> 等价物

unit-testing - 测试类似的逻辑

ios - swift 3 : Caching images in a collectionView

ios - 为新的 View Controller 创建一个类

c# - 为 Container->(Container)->Item 设计通用数据结构/存储

java - 为什么在函数式接口(interface)中使用下界

c# - 用动态语言实现访问者模式的首选方法?

Android MVVM 设计模式

Swift - 如何将 popViewController 动画化为两个 View 返回

Swift: Trying to print an empty string – 该过程已返回到表达式评估之前的状态