Last active
November 12, 2015 18:34
-
-
Save mhuusko5/6f982cd8653d937f3b3a to your computer and use it in GitHub Desktop.
Swift – func associatedValueForEnum(enumm: Any, atIndex index: Int) -> Any?
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 caseLabelForEnum(enumm: Any) -> String { | |
let mirror = Mirror(reflecting: enumm) | |
return mirror.children.first?.label ?? String(enumm) | |
} | |
func associatedValueForEnum(enumm: Any) -> Any? { | |
let mirror = Mirror(reflecting: enumm) | |
return mirror.children.first?.value | |
} | |
func associatedValueForEnum(enumm: Any, atIndex index: Int) -> Any? { | |
guard let associatedValues = associatedValueForEnum(enumm) else { | |
return nil | |
} | |
let valuesMirror = Mirror(reflecting: associatedValues) | |
guard valuesMirror.displayStyle == .Tuple else { | |
if index == 0 { | |
return associatedValues | |
} | |
return nil | |
} | |
let values = Array(valuesMirror.children) | |
guard index < values.count else { | |
return nil | |
} | |
return values[index].value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment