Last active
          April 2, 2017 19:04 
        
      - 
      
 - 
        
Save brokaw/ea159791ca4a88f6dae989d817b99e71 to your computer and use it in GitHub Desktop.  
    Learning Swift sequence protocols
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | struct FibIterator: IteratorProtocol { | |
| var currentCount = 0 | |
| var maxCount: Int? | |
| var maxValue: Int? | |
| var currentFib: Int | |
| var previousFib: Int | |
| mutating func next() -> Int? { | |
| if let maxCount = maxCount, currentCount >= maxCount { | |
| return nil | |
| } | |
| let next = currentFib + previousFib | |
| if let maxValue = maxValue, next > maxValue { | |
| return nil | |
| } | |
| previousFib = currentFib | |
| currentFib = next | |
| currentCount += 1 | |
| return next | |
| } | |
| init(current: Int = 1, previous: Int = 0, count: Int? = nil, max: Int? = nil) { | |
| currentFib = current | |
| previousFib = previous | |
| maxCount = count | |
| maxValue = max | |
| } | |
| } | |
| struct FibSequence: Sequence { | |
| let max: Int? | |
| let count: Int? | |
| func makeIterator() -> FibIterator { | |
| return FibIterator(count: count, max: max) | |
| } | |
| init(count: Int? = nil, max: Int? = nil) { | |
| self.max = max | |
| self.count = count | |
| } | |
| } | |
| // Simple | |
| var last = 0 | |
| var current = 1 | |
| let fibIter = AnyIterator<Int> { | |
| defer { | |
| var next = last + current | |
| last = current | |
| current = next | |
| } | |
| return last | |
| } | |
| let fibSeq = IteratorSequence(fi) | |
| Array(fibSeq.prefix(10)) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment