I am new to Swift and just came across feature of enums in swift that it can have computed properties but not stored properties Why enums does not have stored property in swift ?
1 Answers
Enums are a structured data type. They can have stored value type
properties (so static
properties for example) but they can not have instance properties like an object would have. Also computed properties allow the return of a different value for each case
of the enum, which often vary.
From apple docs
A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.
All structures and enumerations are value types in Swift. This means that any structure and enumeration instances you create—and any value types they have as properties—are always copied when they are passed around in your code.
Because enums are copied every time they are assigned they can not have instance variables such as a reference type
would. The difference being that reference types reference the same instance instead of being copied. Enums are defined by case so their values will always be the same.
Edit:
An important difference between structs and enums is that structs CAN have stored properties. Each case in an enum can have different associated values but each value of an enum type represents a single case as defined by the enum. So by definition an enum case should never change values.
Struct: Value type, can have stored properties
Enum: Value type, can not have stored properties
Class: Reference type, have stored properties

- 1,143
- 7
- 7
-
thanks for such a quick reply but i still have a doubt as in what is the technical reason behind this. why they can not have instance stored properties? – Bushra Sagir Jul 22 '16 at 13:35
-
1Edited the answer with more info – Max Jul 22 '16 at 15:15
-
As structures are also value type like enum but they have stored properties . So as per your answer structures should also not have stored instance properties. please correct me if i am missing something. – Bushra Sagir Jul 25 '16 at 06:24