Last active
September 13, 2018 15:39
-
-
Save yuchi/b6d751272cf4cb2b841f to your computer and use it in GitHub Desktop.
Swift extension that gives Dictionaries support for .map
This file contains hidden or 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 /* <KeyType, ValueType> */ { | |
func mapKeys<U> (transform: KeyType -> U) -> Array<U> { | |
var results: Array<U> = [] | |
for k in self.keys { | |
results.append(transform(k)) | |
} | |
return results | |
} | |
func mapValues<U> (transform: ValueType -> U) -> Array<U> { | |
var results: Array<U> = [] | |
for v in self.values { | |
results.append(transform(v)) | |
} | |
return results | |
} | |
func map<U> (transform: ValueType -> U) -> Array<U> { | |
return self.mapValues(transform) | |
} | |
func map<U> (transform: (KeyType, ValueType) -> U) -> Array<U> { | |
var results: Array<U> = [] | |
for k in self.keys { | |
results.append(transform(k as KeyType, self[ k ] as ValueType)) | |
} | |
return results | |
} | |
func map<K: Hashable, V> (transform: (KeyType, ValueType) -> (K, V)) -> Dictionary<K, V> { | |
var results: Dictionary<K, V> = [:] | |
for k in self.keys { | |
if let value = self[ k ] { | |
let (u, w) = transform(k, value) | |
results.updateValue(w, forKey: u) | |
} | |
} | |
return results | |
} | |
} |
This file contains hidden or 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
// key, value in dictionary | |
[ 0: 1, 2: 5, 8: 10 ].map({ (k, v) in k + v }) // -> [ 1, 7, 18 ] | |
// value in dictionary | |
[ 0: 1, 2: 5, 8: 10 ].map({ v in v * 2 }) // -> [ 1, 10, 20 ] | |
// key, value in dictionary to dictionary | |
[ 0: 1, 2: 5, 8: 10 ].map({ (k, v) in (v, k) }) // -> [ 1: 0, 5: 2, 10: 8 ] |
Yes. In my opinion they should have choose something in the #(a: String) -> String { s }
form, but it’s very succinct anyway.
👍
@jmnavarro That’s very old code! What are you looking at?! :P
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just paste it in the playground to play with it :)