According to sequences and IteratorProtocol in Swift

I am trying to write my own version IndexingIteratorto increase understanding Sequence. I have not assigned any type to map Iterator in my structure. However, the compiler does not complain about this, and I get a standard implementation makeIterator.

Below are my codes:

struct __IndexingIterator<Elements: IndexableBase>: Sequence, IteratorProtocol {
    mutating func next() -> Elements._Element? {
        return nil
    }
}
let iterator = __IndexingIterator<[String]>()
// this works and returns an instance of __IndexingIterator<Array<String>>. why?
iterator.makeIterator() 

I think there Sequenceshould be some extensions that add a default implementation. So I searched it in Sequence.swiftand just found it.

extension Sequence where Self.Iterator == Self, Self : IteratorProtocol {
  /// Returns an iterator over the elements of this sequence.
  public func makeIterator() -> Self {
    return self
  }
}

I thought it would be like this:

extension Sequence where Self: IteratorProtocol {
    typealias Iterator = Self
    ...
}

Am I missing something or misunderstood the extension?

+4
source share
3 answers

, Element next().

:

protocol ResourceProvider {
    associatedtype Resoruce
    func provide() -> Resoruce;
}

struct StringProvider {
    func provide() -> String { // "Resource" inferred to be "String"
        return "A string"
    }
}
0

, . Sequence:

protocol MySequence {
    associatedtype Iterator: IteratorProtocol
    func maakeIterator() -> Iterator
}

extension MySequence where Self.Iterator == Self, Self : IteratorProtocol {
    /// Returns an iterator over the elements of this sequence.
    func maakeIterator() -> Self {
        return self
    }
}

struct __IndexingIterator<Element>: MySequence, IteratorProtocol {
    mutating func next() -> Element? {
        return nil
    }
}

let iterator = __IndexingIterator<[String]>()
iterator.maakeIterator()
0

You can write your own Iterator, which will first go to IteratorProtocol, and then write what you need to confrom for Sequence.

Make sure you need to implement the requried function.

   struct IteratorTest : IteratorProtocol {
        typealias Element = Int

        var count : Int

        init(count :Int) {
            self.count = count
        }

        mutating func next() -> Int? {
            if count == 0 {
                return nil
            }else {
                defer {
                    count -= 1
                }
                return count;
            }
        }
    }

    struct CountDown : Sequence {
        typealias Iterator = IteratorTest
        func makeIterator() -> IteratorTest {
            return IteratorTest.init(count: 10)
        }
    }
0
source

Source: https://habr.com/ru/post/1661138/


All Articles