Basically, Swift does not allow me to do this:
class stored properties not supported in classes did you mean 'static'.
class var hello = "hello"
However this is fine:
static var hi = "hi"
I know that the difference between Class and Static in Swift is that Class variables cannot store stored properties, while Static variables can. However, the fundamental difference between Class and Static variables is that static variables cannot be overridden in subclasses, while class variables can. This is a functionality that I wish to keep.
I know that a simple fix to this issue is to make this a computed property using a hacky fix like this:
class var Greeting : String { return "Greeting" }
This does solve the problem, and I hope it helps some people online as well. However, I would like to know if anyone knows why Swift behaves this way, and does not allow for stored properties in class level variables.
The problem is related to the nature of the static keyword: Every instance of the extended class will share the same static value from the Holder struct. We can use a little bit of imagination in order to be creative and solve the issue.
Extensions can add new computed properties, but they can't add stored properties, or add property observers to existing properties.
We can't add the stored properties to extensions directly but we can have the computed variables . Extensions in Swift can: Add computed instance properties and computed type properties.
class
and a static
member of your class?In both case the member belongs to the Class
type itself (not the instance) but with a tiny difference: class members can be overridden by subclasses.
The answer is:
Yes, a method
of course can be overridden so you can mark it with the class
modifier
class Animal { class func name() -> String { return "Animal" } } class Dog: Animal { override class func name() -> String { return "Dog" } } Animal.name() // Animal Dog.name() // Dog
A computed property is a special kind of method. In fact, it is basically a syntactic sugar for a method that accepts 0 parameters and returns a value.
class Animal { class var name: String { return "Animal" } } class Dog: Animal { override class var name: String { return "Dog" } } Animal.name // Animal Dog.name // Dog
That's why you can add the class
modifier only to methods and computed properties.
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