Skip to content

Instantly share code, notes, and snippets.

@yuchi
Last active September 13, 2018 15:39
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuchi/b6d751272cf4cb2b841f to your computer and use it in GitHub Desktop.
Save yuchi/b6d751272cf4cb2b841f to your computer and use it in GitHub Desktop.
Swift extension that gives Dictionaries support for .map
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
}
}
// 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 ]
@yuchi
Copy link
Author

yuchi commented Jun 3, 2014

Just paste it in the playground to play with it :)

@yuchi
Copy link
Author

yuchi commented Jun 4, 2014

Yes. In my opinion they should have choose something in the #(a: String) -> String { s } form, but it’s very succinct anyway.

@jmnavarro
Copy link

👍

@yuchi
Copy link
Author

yuchi commented Feb 10, 2016

@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