25

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.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
haxgad
  • 387
  • 4
  • 9
  • 3
    I'm trying to understand your question: Are you concerned about why you cannot use the `class` keyword with a type stored property, even though the `static` keyword accomplishes precisely what you want? As an aside, given that you can have type properties in both `class` and `struct` types, wouldn't it be weird to use `class` keyword within a `struct`? – Rob Jul 28 '17 at 18:17
  • Except it doesn't do precisely what the question describes, because the result is different if you have subclasses. And since structs can't have inheritance, they don't apply here. – Tom Harrington Jul 28 '17 at 18:39
  • Compare https://stackoverflow.com/q/45467329/2976878 – I don't believe there's any real reason why this isn't possible. – Hamish Sep 09 '17 at 21:45

1 Answers1

13

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.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148