Skip to content

Instantly share code, notes, and snippets.

@mhuusko5
Last active November 12, 2015 18:34
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/6f982cd8653d937f3b3a to your computer and use it in GitHub Desktop.
Save mhuusko5/6f982cd8653d937f3b3a to your computer and use it in GitHub Desktop.
Swift – func associatedValueForEnum(enumm: Any, atIndex index: Int) -> Any?
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