Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@plumhead
Created April 29, 2015 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plumhead/832ee5226f26f76e8d57 to your computer and use it in GitHub Desktop.
Save plumhead/832ee5226f26f76e8d57 to your computer and use it in GitHub Desktop.
Pairwise in Swift
func pairwise<T>(d: [T]) -> [(T,T)] {
switch d.count {
case 0: return []
case 1: return []
case let n:
let r = [(d[0],d[1])]
return r + pairwise(Array(d[1..<n]))
}
}
let info = [1,2,3,4,5,6]
let info2 = ["A","B","C","D"]
pairwise(info) // (1,2) (2,3) (3,4) (4,5) (5,6)
pairwise(info2) // (A,B) (B,C) (C,D)
pairwise([Int]()) // []
pairwise(["A"]) // []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment