swift - 在类上定义存储类型属性

标签 swift

<分区>

我是 Swift 菜鸟,在阅读“The Swift Programming Language”引用书(语言指南 > 属性 > 类型属性)中的这段时发现自己感到困惑:

“For value types (that is, structures and enumerations), you can define stored and computed type properties. For classes, you can define computed type properties only.”

摘自:Apple Inc.“The Swift Programming Language”。电子书。 https://itun.es/br/jEUH0.l

但是在此之后的几页中,可以找到以下代码片段:

...
class SomeClass {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        // return an Int value here
    }
    class var overrideableComputedTypeProperty: Int {
        // return an Int value here
    }
}
...

在类上下文中明确定义存储类型属性的地方,这显然否定了前面所述的内容。

那么,这是文档错误还是我只是遗漏了什么?

编辑 1

我觉得这不是 this question 的副本.我不是在问为什么这个功能没有实现,因为显然它目前已经实现了(因为编译器不会将其识别为错误)。我要问的是文档操作系统是否过时或我的解释不正确。

编辑2

此问题已得到解决 here .显然文档已经过时了。此功能是在 Swift 1.2 上添加的

最佳答案

我相信文档的意思(以一种相当困惑的方式)是你不能让 class 存储变量(但你仍然可以让 static 存储变量)。

总结一下

class Foo {
  static var bar: Int {      // ok (computed static type variable)
    return 2
  }
  static var foo = ""        // ok (stored static type variable)
  class var foobar: Int {    // ok (computed class type variable)
    return 2
  }
  class var baz = ""         // nope (stored class type variable)
}

关于swift - 在类上定义存储类型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31433810/

相关文章:

ios - 在删除一行 UITableView 之前发出警告

ios - UIImage 不会显示在屏幕上

ios - 快速搜索栏 Controller

swift - 方法不会覆盖 Swift3 中其父类(super class)的任何方法?

android - Android TableLayout/TableRow 的 iOS/Swift 编程等效项

ios - 如何使用 Swift 3 在泛型函数中获取计算变量的子类版本?

快速移动范围 2 或排除找到的字符

ios - 我如何替换 #define 以用于常见的 swift 和 objective-c 使用

ios - 困惑 : Non-nil value unwrapped nil, if-let 子句在 nil 值上执行 block

ios - 防止 Sprite 加速