What's the benefit of Apple having used struct with static properties (instead of enum) for UITextContentType?

Viewed 126

In Swift, Apple's UITextContentType is a struct with many static properties of type UITextContentType such as:

  • static let URL: UITextContentType
  • static let addressCity: UITextContentType
  • static let addressCityAndState: UITextContentType

etc.

But UIKit/UITextInputTraits.h has:

typedef NSString * UITextContentType NS_TYPED_ENUM;

And I notice that within Swift, the compiler infers UITextContentType, allowing you to simply use .URL or .addressCityAndState instead of UITextContentType.URL or UITextContentType.addressCityAndState for any function argument that takes type UITextContentType (thereby treating it just like an enum).

So why didn't they just use an enum to begin with? What's the advantage of using this pattern...? When would we want to use this pattern in our own code?

1 Answers

I've noticed Apple does this with SKAction as well. Every action is a static property. I wish they had used enum in this case. ha

There are a few differences between Static Properties and Enum Cases.
But really it's up to you with how you want to use them.


Pros of Static Properties
• You don't have to make a switch statement every time you want a raw value
• Raw Values can contain mutating non-literal values.
• Static Properties can be whatever type you want it to be static let a = 5, b = false
• You can add static properties to enums, structs, classes, protocols

Cons of Static Properties
• They can not have 'stored properties' like non-static values
• They are not CaseIterable


Pros of Enum
• You can store values inside cases case hello(String, [Bool])
• You can have recursive stored properties using indirect enum
• Cases can be CaseIterable

Cons of Enum
• You cannot have multiple rawValue types case foo = "5", bar = 5
• Raw Value types cannot contain values. case foo = "\(5)"
• Those tricky switch case statements everywhere
• You cannot add enum cases to non-enum objects

Related