Joh*_*ney 37 language-design swift
通过Swift编程语言,我惊讶地发现,与结构和枚举不同,类不支持存储的类型属性.
这是其他OO语言的一个共同特征,所以我认为他们有一个很好的理由决定不允许它.但我无法猜出这是什么原因,特别是因为结构(和枚举)有它们.
难道只是它是Swift的早期时代,它尚未实现吗?或者语言设计决策背后有更深层次的原因吗?
BTW,"存储类型属性"是Swift术语.在其他语言中,这些可能被称为类变量.示例代码:
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"
Run Code Online (Sandbox Code Playgroud)
编辑:
我现在意识到这种限制很容易解决,例如,通过使用具有存储属性的嵌套结构:
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"
Run Code Online (Sandbox Code Playgroud)
这似乎排除了他们成为这种限制的深刻不可思议的语言设计理由.
鉴于这一点以及Martin Gordon提到的编译器消息的措辞,我必须得出结论,这只是遗漏了一些东西(次要的).
Mar*_*don 27
编译器错误是"尚未支持的类变量",所以看起来他们还没有实现它.
Ric*_*aez 15
扩展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 }
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
println(ClassWithTypeProperty.aTypeProperty)
// Prints "hello world"
ClassWithTypeProperty.aTypeProperty = "goodbye cruel world"
println(ClassWithTypeProperty.aTypeProperty)
// Prints "goodbye cruel world"
Run Code Online (Sandbox Code Playgroud)
对于值类型(即结构和枚举),您可以定义存储和计算的类型属性。对于类,您只能定义计算的类型属性。”
摘自:Apple Inc.“快速编程语言”。iBooks。https://itun.es/cn/jEUH0.l
我认为对于Apple的工程师来说,将存储的类型属性添加到类很容易,但是我们还不知道,也许在我看来从来没有。这就是为什么有标签(static和class)来区分它们的原因。
最重要的原因可能是:
为避免不同的对象共享可变变量
我们知道 :
static let storedTypeProperty = "StringSample" // in struct or enum ...
Run Code Online (Sandbox Code Playgroud)
可以替换为
class var storedTypeProperty:String {return "StringSample" } // in class
Run Code Online (Sandbox Code Playgroud)
但
static var storedTypeProperty = "StringSample"
Run Code Online (Sandbox Code Playgroud)
在课堂上很难用课堂短语代替。
//实际上,我是Swift编程语言的新手,这是我在Stack OverFlow中的第一个答案。很高兴与您讨论。^^