Advertisement
SEEEEEAAAAAA10000000

Some generics stuff

Aug 13th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.98 KB | None | 0 0
  1. /// [1, 2, 3, 4, 5] -> [[1,2], [2,3], [3,4], [4,5]]
  2.  
  3. public func makeClosePairs<C: Collection>(c: C) -> [C.SubSequence] {
  4.    
  5.     var out: [C.SubSequence] = []
  6.    
  7.     var index = c.startIndex
  8.     while index < c.endIndex {
  9.         let first = index
  10.         let second = c.index(after: first)
  11.         guard second < c.endIndex else { break }
  12.         let slice = c[first...second]
  13.         out.append(slice)
  14.         index = second
  15.     }
  16.    
  17.     return out
  18.    
  19. }
  20.  
  21. /// [1, 2, 3, 4, 5, 6] -> [1, 2, 3] [4, 5, 6]
  22.  
  23. func sliceOnTwo<D: Collection>(collection: D) -> (left: D.SubSequence, right: D.SubSequence)
  24.     where D.Index: Strideable, D.Index.Stride: SignedInteger
  25. {
  26.     let distance = collection.startIndex.distance(to: collection.endIndex)
  27.     let middlecount = distance / 2
  28.     let middle = collection.startIndex.advanced(by: middlecount)
  29.     let firsthalf = collection[...middle]
  30.     let secondhalf = collection[middle...]
  31.     return (left: firsthalf, right: secondhalf)
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement