Daniil Korotin
Daniil Korotin

Reputation: 730

Stored type properties for classes in 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.

Upvotes: 6

Views: 1524

Answers (2)

Martin R
Martin R

Reputation: 539775

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.

Upvotes: 8

GoZoner
GoZoner

Reputation: 70165

The documentation does seem inconsistent with both the examples in the book and actual code. Here is a REPL example:

  1> class Foo { 
  2.     static var _bar = 8 
  3.     static var bar : Int { return _bar } 
  4. } 
  5> Foo.bar
$R0: Int = 8
  6>  

There is clearly a type property defined.

Upvotes: 0

Related Questions