我有一个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: 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
}
关于如何解决上述编译错误的任何想法?
答案 0 :(得分:5)
您必须将默认值定义为静态属性:
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)编译,增加了支持
用于静态计算属性。在早期版本中,您可以定义
嵌套struct
包含属性作为变通方法(比较
Class variables not yet supported):
class SuperDuperCoolClass : UIViewController {
struct Constants {
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 = Constants.primaryColor){
}
}
答案 1 :(得分:0)
由于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
}