我一直在尝试在类中使用常量和变量,这些类通过名称引用类级别的同一类中的其他常量和变量。 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];
}
答案 0 :(得分:20)
您收到的两条错误消息实际上是两个不同但相关原因的结果。
self
是指类型的实例,在该类型被视为完全初始化之前不存在,因此不能用于默认属性值。
类变量和静态变量被认为是"类型变量"类和结构分别。这意味着它们被定义为类型本身上的变量,而不是该类型的实例。根据此定义以及您无法使用self
作为默认属性值的事实,很明显此错误消息是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编程语言的章节。