Swift: using a constant constant as the default value for a function parameter

I have a quick class in which I am trying to pass the default value for a function parameter:

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

As stated above, if I try to use a constant as the default value for a function parameter, the compiler complains with the error below:

SuperDuperCoolClass.Type does not have a member named 'primaryColor'

but if I directly assign the RHS value in this way, he will not complain: - /:

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
    }

Any ideas on how to silence the above compilation error?

+4
source share
2 answers

You must define the default value as a static property:

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

All Articles