Skip to content

Instantly share code, notes, and snippets.

@qmchenry
Created April 21, 2017 18:07
Show Gist options
  • Save qmchenry/a3b317a8cc47bd06aeabc0ddf95ba113 to your computer and use it in GitHub Desktop.
Save qmchenry/a3b317a8cc47bd06aeabc0ddf95ba113 to your computer and use it in GitHub Desktop.
Swift enum name string with associated values
// Swift enums cannot be declared with a rawValue if they have associated values
// like good ol' Amargasaurus has. Using String(describing: dino) on a case with
// associated also includes the values, but works fine on unassociated cases.
// Mirror(reflecting: dino) can extract the name of an associated case, but is
// nil for unassociated cases. Our hero ?? swoops in to save the day!
enum Sauropoda {
case Amargasaurus(things: Int64, hasOtherThing: Bool?)
case Antetonitrus
// ...
case Titanosauriformes
case Vulcanodon
var caseName: String {
return Mirror(reflecting: self).children.first?.label ?? String(describing: self)
}
}
let v = Sauropoda.Vulcanodon
print(String(describing: v))
// Vulcanodon
print(Mirror(reflecting: v).children.first?.label)
// nil
print(v.caseName)
// Vulcanodon
let a = Sauropoda.Amargasaurus(things: 314, hasOtherThing: nil)
print(String(describing: a))
// Amargasaurus(things: 314, hasOtherThing: nil)
print(Mirror(reflecting: a).children.first?.label)
// Optional("Amargasaurus")
print(a.caseName)
// Amargasaurus
@qmchenry
Copy link
Author

Glad it helped! :)

@tamimattafi
Copy link

Thank you! Now I understand when to use each one of the String constructors

@bespalown
Copy link

Thank you! With this decision, I will go through a Revue in the store?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment