我一直在尝试在类中使用常量和变量,这些常量和变量在类级别上按名称引用同一类中的其他常量和变量。AFAIK,从Xcode 6 beta 4开始,Swift仍然没有类变量支持。我想知道的是,当我尝试引用其他常量(let)或变量(var)时看到的错误是否仅仅是由于缺少类变量支持?
您可以在方法内或类外部引用常量和变量,只是似乎无法在类级别按名称引用。下列类别显示了几种变体,以及将在Xcode 6 beta 4中显示的错误。
可以在游乐场或常规.swift文件中进行测试。
class Simple { let someConstant = 0.50 var someVariable = 1 // uncomment let and var lines to see the errors // error: 'Simple.Type' does not have a member named 'someConstant' // let referringConstant = someConstant // error: Use of unresolved identifier 'self' // let referringConstant = self.someConstant // error: 'Simple.Type' does not have a member named 'someVariable' // var referringVar = someVariable // error: Use of unresolved identifier 'self' // var referringVar = self.someVariable // can't do class constants or variables yet either // let referringConstant = Simple.someConstant // var referringVar = Simple.someVariable func simpleMethod() { // both of these forms are valid as long as it is unambiguous let referToConstant = someConstant let referToVariable = someVariable var anotherConstant = self.someConstant var anotherVariable = self.someVariable } }
作为参考,导致Swift中出现此问题的原始Objective-C代码来自CS193P SuperCard应用,其中C
@interface PlayingCardView() @property (nonatomic) CGFloat faceCardScaleFactor; @end @implementation PlayingCardView #pragma mark - Properties @synthesize faceCardScaleFactor = _faceCardScaleFactor; #define DEFAULT_FACE_CARD_SCALE_FACTOR 0.90 - (CGFloat)faceCardScaleFactor { if (!_faceCardScaleFactor) _faceCardScaleFactor = DEFAULT_FACE_CARD_SCALE_FACTOR; return _faceCardScaleFactor; } - (void)setFaceCardScaleFactor:(CGFloat)faceCardScaleFactor { _faceCardScaleFactor = faceCardScaleFactor; [self setNeedsDisplay]; }
您收到的两个错误消息实际上是两个不同但相关的原因的结果。
self 引用类型的实例,并且在该类型被认为已完全初始化之前不存在,因此不能用于默认属性值。
self
类变量和静态变量分别被视为类和结构的“类型变量”。这意味着将它们定义为 类型本身 上的变量,而不是该类型的实例。根据这个定义以及您不能使用self默认属性值的事实,很明显,此错误消息是Swift寻找名为的类变量的结果someConstant。自Beta 4起,仍不支持类变量。
someConstant
考虑到类型变量的类似结构的代码可以很好地编译:
struct Simple { static let someConstant = 0.50 static var someVariable = 1 let referringConstant = someConstant var referringVar = someVariable let explicitTypeProperty = Simple.someConstant }
参考:我对 Swift编程语言 的“属性”和“初始化程序”章节的回忆。