1

I'm trying to understand something about type properties in swift.

The Swift Programming Language says

For classes, you can define computed type properties only

So a computed property does not store a value itself, but it is calculated. That I understand. But I don't get how such a thing can apply to type properties. Such properties belong to the class itself and not to an instance of it.

So if you use a getter for such a computed type property, what could you possibly use to calculate it? It can't be any other type properties, as they too can only be computed properties. You would get a sort of loop of computed properties because there aren't any stored type properties.

In the same way, I also don't get what a setter would do. If you call the setter of a computed type property, what can it set? There are no stored type properties to be set.

Felix Frank
  • 8,125
  • 1
  • 23
  • 30

1 Answers1

3

Bear in mind that stored class properties are only unsupported at the moment. The compiler error you get when you try to use them—"Class variables not yet supported"— suggests that they're on their way. Computed class properties don't necessarily have to make sense on their own.

However, computed properties don't always have to be based on the values of stored data. As it stands, you could use them for "static" read-only values associated with the class, say:

    class var ThisIsAClassConstant: String  { return "Woo" }

And people have already come up with ways to store associated values, for example, in the first two singleton patterns in this answer, the class property stores its state in either a global (but private) variable, or in a static variable inside a nested structure.

These are obviously a bit "workaroundy", but they're a way of achieving class-like storage while it's not officially implemented.

Community
  • 1
  • 1
Matt Gibson
  • 37,886
  • 9
  • 99
  • 128