-1
private enum ViewMetrics {
    static let fontSize: CGFloat = 24.0
    static let spacing: CGFloat = 16.0
}

Can you explain this for me?

How can we write an enum without cases and how it is possible to define static properties in an enum. I did not find this topics in apple official guide. Can anyone help me with the correct reference to know this topic.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116

2 Answers2

2

Why shouldn't you be able to do this?

Swift enums are first-class types, just like structs and classes. Swift enums do not need to have cases, they can be completely empty types, just like how a struct or class does not need to have any properties.

enum Empty {} // completely valid

enums cannot have _ stored instance properties_, but they can have type properties (which static properties are) and computed instance properties.

Caseless enums with static properties are often used for storing constant values. For more information on the topic, see Swift constants struct or enum

This might not be documented in the Enumerations section of the Swift docs, but nothing says that this shouldn't be possible either. On the other hand, the docs do state that enums are first-class types and there is a non-exhaustive list of features that enums share with classes and structs.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

An enum without any case can have static properties because they are not related to a case of the enum. Just like a struct without any properties or an empty class having a static properties. static is not based on an instance of something.

Here is the link for swift documentation which explains clearly about instance and static properties.

Frankenstein
  • 15,732
  • 4
  • 22
  • 47