Skip to content

Instantly share code, notes, and snippets.

@mhuusko5
Created October 19, 2015 12:25
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 mhuusko5/e169eee85c379fb4f86a to your computer and use it in GitHub Desktop.
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]?
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