Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored type properties for classes in Swift

Tags:

ios

swift

I've seen similar questions on SO, but none actually has the answer to this question. "The Swift Programming Language" book (v. 1.2) says:

For classes, you can define computed type properties only

And then on the next page they have the following example (I got rid of some code for the sake of brevity):

class SomeClass {
    static var storedTypeProperty = "Some value."
    // ...
}

Even the name of variable says it's a stored type property (not a computed one).

Update: You can define stored properties for classes, see the detailed answer below. Turned out the book wasn't updated with the changes in Swift 1.2 for this part.

like image 542
Daniil Korotin Avatar asked May 14 '15 16:05

Daniil Korotin


1 Answers

Static stored properties in classes were introduced with Swift 1.2. The Xcode 6.3 Release Notes list under Swift Language Enhancements (emphasis added):

static” methods and properties are now allowed in classes (as an alias for class final). You are now allowed to declare static stored properties in classes, which have global storage and are lazily initialized on first access (like global variables).

The example

class SomeClass {
    static var storedTypeProperty = "Some value."
    // ...
}

is an example for a static property of a class. The statement

For classes, you can define computed type properties only

is not correct, it has not yet been updated according to this language change.

like image 73
Martin R Avatar answered Sep 21 '22 00:09

Martin R