如何实现sequence

//先构造iterator
class ReverseIterator: IteratorProtocol {
    var array: [T]
    var currrentIndex = 0
    init(arr:[T]) {
        self.array = arr
        currrentIndex = arr.count-1
    }
    
    func next() -> T? {
        if currrentIndex < 0{
            return nil
        }else{
            let index = currrentIndex
            currrentIndex = currrentIndex - 1
            return array[index]
        }
    }
    typealias Element = T
}

//构造
class ReverseSequence: Sequence {
    var array: [T]
    
    init(arr:[T]) {
        self.array = arr
    }
    typealias Iterator = ReverseIterator
    func makeIterator() -> ReverseIterator {
        return ReverseIterator(arr: self.array)
    }
}

for (index,value) in ReverseSequence(arr: ["11231","2da","good"]).enumerated() {
    print(index,value)
}

//0 good
//1 2da
//2 11231

你可能感兴趣的:(如何实现sequence)