Swift: 使用成员常量作为函数参数的默认值

Swift: using member constant as default value for function parameter

我有一个 swift class,我试图在其中传递函数参数的默认值:

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
    }

关于如何消除上述编译错误的任何想法?

您必须将默认值定义为 static 属性:

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){
    }
}

由于 primaryColor 是一个实例变量,只有从这个 class 创建一个实例才能访问它,并且由于该函数是 class 定义的一部分,您将收到此错误因为 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
    }