我一直在尝试在一个类中使用常量和变量,该类通过名称引用到类级别的同一个类中的其他常量和变量. 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#define用于常量,然后该常量用于设置变量.
@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是指类型的实例,不存在,直到该类型被认为是完全初始化为止,因此不能用于默认属性值.
错误:’Simple.Type’没有名为’someConstant’的成员
类变量和静态变量分别被认为是类和结构体的“类型变量”.这意味着它们被定义为类型本身的变量,而不是该类型的实例.通过这个定义和事实,你不能使用自己的默认属性值,很明显,这个错误信息是Swift寻找名为someConstant的类变量的结果. Beta 4中仍然不支持类变量.
结构体的类似代码,考虑了类型变量,编译得很好:
struct Simple { static let someConstant = 0.50 static var someVariable = 1 let referringConstant = someConstant var referringVar = someVariable let explicitTypeProperty = Simple.someConstant }
参考:我对“Swift编程语言”的“属性”和“初始化程序”章节的回忆.