Skip to content

Instantly share code, notes, and snippets.

@mhuusko5
Created October 19, 2015 12:23
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/df99f88832c86f8a1736 to your computer and use it in GitHub Desktop.
Save mhuusko5/df99f88832c86f8a1736 to your computer and use it in GitHub Desktop.
Swift – func asArray<T>(any: Any, type: T.Type = T.self) -> [T]?
func asArray<T>(any: Any, type: T.Type = T.self) -> [T]? {
let mirror = Mirror(reflecting: any)
let properties = Array(mirror.children)
guard let displayStyle = mirror.displayStyle where (displayStyle == .Collection || displayStyle == .Set || displayStyle == .Tuple) else {
return nil
}
var array = [T]()
for property in properties {
if let value = property.value as? T {
array.append(value)
} else {
return nil
}
}
return array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment