Constants: Struct static lets or enums?
Organizing constant values in code has been important since before Swift, but provides several ways.
The goals is to fins a way to organize, very readable, esaiy to use and maintain.
The first way that was suggested, ealy in Swift, is to use an enum with a raw value:
enum StoryboardID : String {
case main
case profile
case edit
}
This usage was popular enough that for Strings, Swift 2 automaticly uses the case name as the raw value. The above is:
let mainStoryboardID = StoryboardID.main.rawValue
// mainStoryboardID == "main"// But: enum SegueID {
case toDetail
case toSettings
case toEdit = "toEditVC" // One case raw value specified
}
However, one minor downside is that to work with the string, you are always going to have to access the `rawValue` property:
let mainStoryboard = UIStoryboard(name: StoryboardID.main.rawvalue, bundle: nil)
Enums come with some other details that could interfear, or at least distract, from their use of constants. For one thing, enums should be able to be used interchangibly.
In most cases when you want to use a constant, you want t create a specific constant, not “any one of this grouping of constants.” Is there a better way to specify this?
##Static Let
Static constants just add constants as static variables (or constants)
struct StoryboardID {
static let main = "main"
static let profile = "profile"
static let edit = "edit"
}
You don’t get the enum’s automatic conversion of the case
into the constant string, but other than that, this is more flexible and specific:
let mainStoryboard = UIStoryboard(name: StoryboardID.main, bundle: nil)
Enums are still useful for checks: Where you know you want one of several possibilities, and need to be able to check which one you have.
guard let segueIDString = segue.identifier, segueID = SegueID(rawValue: segueIDString) else { fatalError("Unknown segue \(segue.identifier)") }switch segueID {
case toDetail: //...
case toSettings: //...
case toEdit: //...
}
The ability to enure that every case if covered is `enum`’s great benefit, and usuing enums just to hold independent values isn’t a good use of them.