Advertisement
Guest User

CollectionType.startsWith() -> Index?

a guest
Feb 5th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.88 KB | None | 0 0
  1. extension CollectionType {
  2.     func startsWith<S : SequenceType where S.Generator.Element == Generator.Element>(other: S, @noescape isEquivalent: (Generator.Element, Generator.Element) throws -> Bool) rethrows -> Index? {
  3.         var index = self.startIndex
  4.        
  5.         // If `self` starts with `other` this will have to iterate over the whole sequence
  6.         for element in other {
  7.            
  8.             // `self` has to be at least as long as `other`, bail out if not
  9.             if index == self.endIndex {
  10.                 return nil
  11.             }
  12.            
  13.             // Bail out if different
  14.             if try isEquivalent(self[index], element) == false {
  15.                 return nil
  16.             }
  17.            
  18.             // The elements match, continue with the next pair
  19.             index = index.successor()
  20.         }
  21.        
  22.         return index
  23.     }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement