Posts

Showing posts from November, 2020

Why implementation of the sequence protocol is said destructive?

Is implementation of sequence protocol , destructive ? Why and how! Sequence type is said to provide sequential, iterated access of its elements.  Think of a sequence generator which can be used to create user id's, from a starting point.   public struct UserIdSequenceGenerator : Sequence {     private var startId : Int          public init (startId: Int ){         self . startId = startId     } } extension UserIdSequenceGenerator : IteratorProtocol {     public mutating func next () -> Int ? {         defer {             startId += 1         }         return startId        } } Requirements on implementing Sequence Protocol. First Approach. Override  make Iterator() method which returns  IteratorProtocol object.   Second Approach Make the UserIdSequenceGenerator Confirm to IteratorProtocol itself and implement next(). We have used second approach in the above code. Finally the code in Action looks like seen below. var sequence = UserIdSequenceGenerator (startId