Working through The Swift Programming Language, I was surprised to see that, unlike structures and enumerations, classes do not support stored type properties.
This is a common feature of other OO languages so I assume there was a good reason they decided not to allow it. But I'm not able to guess what that reason is, especially since structures (and enumerations) have them.
Is it simply that it's early times for Swift and it just hasn't been implemented yet? Or is there a deeper reason behind language design decision?
BTW, "stored type property" is Swift terminology. In other languages these might be called class variables. Example code:
struct FooStruct { static var storedTypeProp = "struct stored property is OK" } FooStruct.storedTypeProp // evaluates to "struct stored property is OK" class FooClass { class var computedClassProp: String { return "computed class property is OK" } // class var storedClassProp = "class property not OK" // this won't compile } FooClass.computedClassProp // evaluates to "computed class property is OK"
Edit:
I now realize this limitation is trivial to work around, e.g., by using a nested structure with stored properties:
class Foo { struct Stored { static var prop1 = "a stored prop" } } Foo.Stored.prop1 // evaluates to "a stored prop" Foo.Stored.prop1 = "new value" Foo.Stored.prop1 // evaluates to "new value"
That seems to preclude their being some deep inscrutable language design reason for this limitation.
Given that and the wording of the compiler message that Martin Gordon mentions, I have to conclude that this is simply something (minor) left out.
A static stored property in a protocol extension would require separate storage for each conforming type of that protocol (but again; there's no reason why the compiler/runtime cannot do this). This is necessary with protocols, as static members in protocol extensions are not members on the protocol type itself.
Stored Properties A stored property is a property whose value is stored as part of the instance of a particular type. Stored properties can be either variable or constant. We can use var to create a variable stored property, and let to create a constant stored property.
As you may know Swift does not allow stored properties into extensions. That's by design: “Extensions may not contain stored properties.”
willSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.
The compiler error is "Class variables not yet supported" so it seems like they just haven't implemented it yet.
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