Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do enums have computed properties but not stored properties in Swift?

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?

like image 599
Adit Gupta Avatar asked Aug 28 '15 19:08

Adit Gupta


People also ask

Why do we need enum 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.

What is computed stored properties in Swift?

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.

How does enum work in Swift?

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.

Can a Swift enum have functions?

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.


1 Answers

enums 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 enums. 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 structs and classes. 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 cases, you get to individualize the stored properties for each case.

like image 112
Aaron Rasmussen Avatar answered Oct 04 '22 05:10

Aaron Rasmussen