Created
October 19, 2015 12:25
-
-
Save mhuusko5/e169eee85c379fb4f86a to your computer and use it in GitHub Desktop.
Swift – func asDictionary<K, V>(any: Any, type: (key: K.Type, value: V.Type) = (K.self, V.self)) -> [K: V]?
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
func asDictionary<K, V>(any: Any, type: (key: K.Type, value: V.Type) = (K.self, V.self)) -> [K: V]? { | |
let mirror = Mirror(reflecting: any) | |
let properties = mirror.children | |
guard let displayStyle = mirror.displayStyle where displayStyle == .Dictionary else { | |
return nil | |
} | |
var dictionary = [K: V]() | |
for property in properties { | |
let pair = Array(Mirror(reflecting: property.value).children) | |
if let key = pair[0].value as? K, let value = pair[1].value as? V { | |
dictionary[key] = value | |
} else { | |
return nil | |
} | |
} | |
return dictionary | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment