Enum or struct?

I often see a pattern where there is an enum with a bunch of computed properties that return a different value for each case. In the rest of the code base then only those properties are used. Something like this:

enum Style { case headline case bodyText case emphasis var isBold: Boolean { switch self { case .headLine, .emphasis: return true case .bodyText: return false } } var fontSize: CGFloat { switch self { case .headline: return 20 case .bodyText, .emphasis: return 16 } } }
Code language: PHP (php)

This works, but quite often can be improved by using a struct instead of an enum. Define a struct which contains all your computed properties as stored properties and the define a global constant of this for each enum case:

struct Style { var isBold: Bool var fontSize: CGFloat static let headline = Style(isBold: true, fontSize: 20) static let bodyText = Style(isBold: false, fontSize: 16) static let emphasis = Style(isBold: true, fontSize: 16) }
Code language: JavaScript (javascript)

This requires less code, it is easier to see and change the values for each case and you can add more cases without having to change the source code of the enum definition.

This doesn’t work in every case though. Better stick to an enum if the identity of the cases is important, for example for control flow. Another issue is (JSON) decoding – the struct would require all the properties in the data.