Swift中类的存储类型属性 [英] Stored type properties for classes in Swift

查看:156
本文介绍了Swift中类的存储类型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO上看过类似的问题,但实际上没有人能回答这个问题。 Swift编程语言一书(v.1.2)说:

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).

更新:您可以定义类的存储属性,请参阅下面的详细解答。原来这本书没有更新Swift 1.2中的这一部分。

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
Xcode 6.3发行说明列表 Swift语言增强(重点补充):

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 现在允许在类中使用方法和属性(作为类最终的
别名
)。您现在可以在类中声明静态存储的
属性
,这些类具有全局存储空间,并且在首次访问时(例如全局变量)初始化为

"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).

示例

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.

这篇关于Swift中类的存储类型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆