Skip to content

Instantly share code, notes, and snippets.

@MartinJNash
Created January 12, 2015 16:33
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 MartinJNash/24b572b59f22e642f929 to your computer and use it in GitHub Desktop.
Save MartinJNash/24b572b59f22e642f929 to your computer and use it in GitHub Desktop.
Functional methods for Swift dictionaries
extension Dictionary {
func map<T>(tx: Element->T) -> [T] {
var memory: [T] = []
for (k, v) in self {
memory.append(tx(k, v))
}
return memory
}
func reduce<T>(var initial: T, tx: (Key, Value, T) -> T) -> T {
for (k, v) in self {
initial = tx(k, v, initial)
}
return initial
}
func filter(pred: Element->Bool) -> Dictionary<Key, Value> {
var memory = Dictionary<Key, Value>()
for (k, v) in self {
if pred(k, v) {
memory[k] = v
}
}
return memory
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment