Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct or Enum to use for serialization keys?

Tags:

ios

swift

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.

like image 264
Sandr Avatar asked Dec 25 '14 17:12

Sandr


2 Answers

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.

like image 71
matt Avatar answered Oct 02 '22 19:10

matt


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.

like image 44
jemmons Avatar answered Oct 02 '22 18:10

jemmons