Created
January 12, 2015 16:33
-
-
Save MartinJNash/24b572b59f22e642f929 to your computer and use it in GitHub Desktop.
Functional methods for Swift dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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