Is there any reason why Apple prefers using structs over enums in the Lister demo for declaring keys for serialization? Is there might be some benefits?
For example:
private struct SerializationKeys {
static let text = "text"
static let uuid = "uuid"
static let completed = "completed"
...
//duplicated key!
static let descriptionText = "text"
}
Here we might have potential duplicates for keys. It's not a big question for small objects (don't forget copy/paste :)), but for large objects with tens fields it can be a real problem.
With enum we don't have such a problem:
private enum SerializationKeys : String {
case text = "text"
case uuid = "uuid"
case completed = "completed"
//...
case descriptionText = "text"
//here we have compiler's warning: Raw value for enum case is not unique
}
Will be happy to hear some thoughts on this.
I do the same thing, sometimes, and here's why.
With a struct, my values are directly available: so, if SerializationKeys is a struct, then SerializationKeys.text
is a string.
But with an enum, the enum is the value. If SerializationKeys is an enum, then SerializationKeys.text
is not a string; it's an enum. If I want the string, I have to fetch it explicitly, as the enum's rawValue
. Sometimes, that's just too nutty. On the other hand, if it's acceptable, or if there's another reason why this makes a good enum, then fine, I'll use an enum.
To put it another way: if this is just a glorified namespace for some constants, a struct with static members seems simplest. An enum is for a switch, i.e. something that needs to exist in exactly one of several possible states.
Apple's reason for choosing a struct
here seems to be purely semantic. SerializationKeys.descriptionText
is a property. SerializationKey.DescriptionText
is a type. And it is kind of semantically weird to use a type as a key.
True, in this particular instance the SerializationKey.DescriptionText
type happens to have a "raw" value associated with it. But as I understand it, raw values are really only intended to be used as a sort of "bridging layer" layer between C enums. Using it for keys like this is kind of a hack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With