Swift : 自定义反向遍历协议

以下摘抄自 Swifter Tips ..

// 实现反向的 Iterater
class ReverseIterator: IteratorProtocol {
    
    typealias Element = T
    var array: [Element]
    var currentIndex = 0
    init(array: [Element]) {
        self.array = array
    }
    
    func next() -> Element? {
        if currentIndex < 0 {
            return nil
        }else {
            let ele = self.array[currentIndex]
            currentIndex -= 1
            return ele
        }
    }
    
}

// 实现反向的 Sequence
struct ReverseSequence: Sequence {
    var array: [T]
    init(array: [T]) {
        self.array = array
    }
    typealias Iterator = ReverseIterator
    func makeIterator() -> ReverseIterator {
        return ReverseIterator(array: self.array)
    }
}

你可能感兴趣的:(Swift : 自定义反向遍历协议)