Skip to content

Instantly share code, notes, and snippets.

@hassanvfx
Created September 5, 2018 04:18
Show Gist options
  • Save hassanvfx/94772f92b6f7630020bd5a7ac8d11d9a to your computer and use it in GitHub Desktop.
Save hassanvfx/94772f92b6f7630020bd5a7ac8d11d9a to your computer and use it in GitHub Desktop.
Swift Loop on Struct Properties
protocol PropertyLoopable
{
func allProperties() throws -> [String: Any]
}
extension PropertyLoopable
{
func allProperties() throws -> [String: Any] {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle where style == .Struct || style == .Class else {
//throw some error
throw NSError(domain: "hris.to", code: 777, userInfo: nil)
}
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else {
continue
}
result[label] = valueMaybe
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment