Created
September 5, 2018 04:18
-
-
Save hassanvfx/94772f92b6f7630020bd5a7ac8d11d9a to your computer and use it in GitHub Desktop.
Swift Loop on Struct Properties
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
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