I am new to Swift and just came across this in the documentation:
Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.
Why is that? Do associated values for enum work like stored properties? It seems like they had stored properties initially - Why no stored type properties for classes in swift?
Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.
Computed properties are for creating custom get and set methods for stored properties. Computed properties are provided by classes, structures, and enumerations to provide custom behavior for properties. Stored and computed properties are usually associated with a particular type but can be associated with any type.
In Swift, an enum (short for enumeration) is a user-defined data type that has a fixed set of related values. Here, Season - name of the enum. spring/summer/autumn/winter - values defined inside the enum.
Cases as functions Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.
enum
s do have stored type properties - i.e., static
properties. They don't have stored instance properties. I don't know if there is a technical reason why stored instance properties are not available for enum
s. You may have to ask your question on the dev forum if you want a technical answer for "why".
In your question you ask if associated values work like stored properties. In fact, they do, and are more flexible (in some ways) than stored properties for struct
s and class
es. Each case
in an enum
can have its own specialized set of data that is associated with it. Rather than have one set of stored properties that apply to all case
s, you get to individualize the stored properties for each case
.
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