Swift:使用成员常量作为函数参数的默认值
我有一个swift类,在该类中我试图传递函数参数的默认值:Swift:使用成员常量作为函数参数的默认值,swift,function-parameter,Swift,Function Parameter,我有一个swift类,在该类中我试图传递函数参数的默认值: class SuperDuperCoolClass : UIViewController { // declared a constant let primaryColor : UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0) // compilation error at below line:
class SuperDuperCoolClass : UIViewController {
// declared a constant
let primaryColor : UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)
// compilation error at below line: SuperDuperCoolClass.Type does not have a member named 'primaryColor'
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = primaryColor){
// some cool stuff with bullet and primaryColor
}
}
如上所述,若我尝试使用常量作为函数参数的默认值,编译器会抱怨以下错误:
SuperDuperCoolClass.Type does not have a member named 'primaryColor'
但是如果我像这样直接分配RHS值,它不会抱怨:-/:
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)) {
// now I can do some cool stuff
}
关于如何消除上述编译错误,您有什么想法吗?您必须将默认值定义为静态属性:
class SuperDuperCoolClass : UIViewController {
static let primaryColor : UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = primaryColor){
}
}
上面的代码使用Swift 1.2(Xcode 6.3)编译,它增加了支持
用于静态计算属性。在早期版本中,可以定义
一个嵌套的结构
,包含属性作为解决方法(比较
):
由于
primaryColor
是一个实例变量,因此在从该类创建实例之前无法访问该变量,并且由于该函数是类定义的一部分,您将收到此错误,因为primaryColor
当时无法访问
您可以使用MartinR方法,也可以使用所需颜色的方法:
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)) {
// now I can do some cool stuff
}
当我试图将常量声明为静态时,出现了以下编译错误:静态属性仅允许在结构和枚举中使用:-|@miraj:我已使用Xcode 6.3测试了代码,这是当前版本。@miraj:是。但我为旧版本添加了一个变通方法。
func configureCheckmarkedBullet(bullet: UIButton, color: UIColor = UIColor(red: 72.0/255.0, green: 86.0/255.0, blue: 114.0/255.0, alpha: 1.0)) {
// now I can do some cool stuff
}