Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are class stored properties not supported in classes?

Tags:

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.

like image 874
haxgad Avatar asked Jul 28 '17 18:07

haxgad


People also ask

Why can't extensions have stored properties?

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.

Can extension have stored property?

Extensions can add new computed properties, but they can't add stored properties, or add property observers to existing properties.

Can we declare variable in extension Swift?

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.


1 Answers

What is the difference between a 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.

Now, which kind of members can be overridden in Swift?

The answer is:

Methods

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 

Computed Properties

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.

like image 177
Luca Angeletti Avatar answered Jan 03 '23 09:01

Luca Angeletti