enum will be preferable for several reasons.
First, enum actually ends up with less memory. This is because Swift optimizes enum values ββby one byte (regardless of the original value), and we only get the full value when we call rawValue by enum value. Paste the following code on the playground to see:
struct LetterSpacingS { static let Short: Double = 1.0 } enum LetterSpacingE: Double { case Short = 1.0 } sizeofValue(LetterSpacingS.Short) sizeofValue(LetterSpacingE.Short)
double is 8 bytes, and enum is only 1.
Secondly, the importance of the first point extends beyond the entire memory. It can also be applied to the effectiveness of our program. If we want to compare two values ββfrom our structure, we compare 8 bytes. If we want to compare our two enum values, we only compare one byte. In this particular case, we have the 1 / 8th number of bytes. And it's just double. Note that Swift strings can also have strings as substitution types. Comparing two strings can be extremely expensive, but just comparing one byte, they are hidden in enum .
Third, using an enumeration, we do not compare floating point numbers that you really do not want to do, generally speaking.
Fourth, using an enumeration gives us some type safety that we cannot get with a constant structure. The entire structure of constants allows you to define several predefined constants to use.
struct LetterSpacingS { static let Short = 1.0 static let Medium = 2.0 static let Long = 3.0 }
But now, what does a method look like that expects one of these values?
func setLetterSpacing(spacing: Double) {
And now, what happens when Joe-Coder comes in and does:
foo.setLetterSpacing(-27.861)
Nothing stops him. Requires double, any double. It may not be so often, but if it is in the library that you distribute, you leave yourself open to questions and comments, for example: "When I pass the value 5.0, it does not look like that at all!"
But compare this with enum .
func setLetterSpacing(spacing: LetterSpacing) {
And now we get only three predefined options for what needs to be passed into this argument.
And outside of your internal use for values ββstored in enum , you will have to use rawValue too much.
The fifth reason is not a serious reason to use an enumeration over a structure, but basically just to eliminate one of the reasons suggested for using a structure over an enumeration. Swift enumerations can be nested in other types, and other types can be nested in Swift lists. You do not need to use struct for nested types.