简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM