Created
April 21, 2017 18:07
-
-
Save qmchenry/a3b317a8cc47bd06aeabc0ddf95ba113 to your computer and use it in GitHub Desktop.
Swift enum name string with associated values
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
// 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 | |
Glad it helped! :)
Thank you! Now I understand when to use each one of the String constructors
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
Thanks for sharing, saved a few time of playgrounding :)