Skip to content

Instantly share code, notes, and snippets.

@cruffenach
Created August 29, 2014 20:38
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 cruffenach/3ed23d6d80ed27fd6928 to your computer and use it in GitHub Desktop.
Save cruffenach/3ed23d6d80ed27fd6928 to your computer and use it in GitHub Desktop.
Index in Array's map and reduce
extension Array {
func map<U>(function : (index : Int, object : T) -> U) -> [U] {
var result = [U]()
for i in 0..<self.count {
result.append(function(index: i, object: self[i]))
}
return result
}
func reduce<U>(initial : U, combine : (product : U, index : Int, object : T) -> U) -> U {
var result = initial;
for i in 0..<self.count {
result = combine(product: result, index: i, object: self[i])
}
return result
}
}
@kazmasaurus
Copy link

I think you're looking for enumerate()

map(enumerate(["a", "b", "c"])) { "\($0) \($1)" } //["0 a", "1 b", "2 c"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment