简体   繁体   English

Swift中类的存储类型属性

[英]Stored type properties for classes in Swift

I've seen similar questions on SO, but none actually has the answer to this question. 我在SO上看过类似的问题,但实际上没有人能回答这个问题。 "The Swift Programming Language" book (v. 1.2) says: “Swift编程语言”一书(v.1.2)说:

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. 原来这本书没有更新Swift 1.2中的这一部分。

Static stored properties in classes were introduced with Swift 1.2 . Swift 1.2引入了类中的静态存储属性。 The Xcode 6.3 Release Notes list under Swift Language Enhancements (emphasis added): Swift语言增强下的Xcode 6.3发行说明列表(重点已添加):

static ” methods and properties are now allowed in classes (as an alias for class final ). 现在允许在类中使用“ static ”方法和属性(作为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: 这是一个REPL示例:

  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. 显然有一个类型属性已定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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