为什么没有swift中类的存储类型属性?

时间:2014-06-04 05:19:45

标签: language-design swift

通过Swift编程语言,我惊讶地发现,与结构和枚举不同,类不支持存储类型属性。

这是其他OO语言的一个共同特征,因此我认为他们有充分的理由决定不允许它。但我无法猜出这是什么原因,特别是因为结构(和枚举)都有它们。

仅仅是Swift的早期时间还没有实现吗?或者语言设计决策背后有更深层次的原因吗?

BTW,"存储类型属性"是斯威夫特的术语。在其他语言中,这些可能被称为类变量。示例代码:

struct FooStruct {
    static var storedTypeProp = "struct stored property is OK"
}

FooStruct.storedTypeProp // evaluates to "struct stored property is OK"

class FooClass {
    class var computedClassProp: String { return "computed class property is OK" }

    // class var storedClassProp = "class property not OK" // this won't compile
}

FooClass.computedClassProp // evaluates to "computed class property is OK"

编辑:

我现在意识到这种限制很容易解决,例如,通过使用具有存储属性的嵌套结构:

class Foo {
    struct Stored {
        static var prop1 = "a stored prop"
    }
}

Foo.Stored.prop1 // evaluates to "a stored prop"
Foo.Stored.prop1 = "new value"
Foo.Stored.prop1 // evaluates to "new value"

这似乎排除了他们成为这种限制的深刻不可理喻的语言设计理由。

鉴于这一点以及Martin Gordon提到的编译器消息的措辞,我必须得出结论,这只是遗漏了一些东西。

3 个答案:

答案 0 :(得分:27)

编译器错误是"尚未支持类变量"所以看起来他们还没有实现它。

答案 1 :(得分:14)

扩展OP的嵌套结构技巧以模拟存储的类型属性,您可以进一步使其看起来像纯存储类型属性来自课外。

使用计算出的 getter setter 对,如:

class ClassWithTypeProperty
{
    struct StoredTypeProperties
    {
        static var aTypeProperty: String = "hello world"
    }

    class var aTypeProperty: String
    {
        get { return self.StoredTypeProperties.aTypeProperty }
        set { self.StoredTypeProperties.aTypeProperty = newValue }
    }
}

然后你可以这样做:

println(ClassWithTypeProperty.aTypeProperty)
// Prints "hello world"

ClassWithTypeProperty.aTypeProperty = "goodbye cruel world"

println(ClassWithTypeProperty.aTypeProperty)
// Prints "goodbye cruel world"

答案 2 :(得分:5)

  

“对于值类型(即结构和枚举),您可以定义存储和计算的类型属性。对于类,您只能定义计算类型属性。"

     

摘自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itun.es/cn/jEUH0.l

我认为Apple的工程师很容易将存储类型属性添加到课程中,但我们还不知道,也许我认为从来没有。这就是为什么有标签(静态)来区分它们的原因。

最重要的原因可能是:

避免不同的对象共享可变变量

我们知道:

static let storedTypeProperty = "StringSample"  // in struct or enum ...

可以替换为

class var storedTypeProperty:String {return "StringSample" }  // in class

但是

static var storedTypeProperty = "StringSample"  

更难被类中的类短语替换。

//我实际上是Swift Programming Language的新手,这是我在Stack OverFlow中的第一个答案。很高兴与您讨论。 ^^