Devarshi
Devarshi

Reputation: 16758

Swift: using member constant as default value for function parameter

I have a swift class, in which I am trying to pass a 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 constant as default value for function parameter, compiler complains with below error:

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

but if I assign the RHS value directly like this, it does 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 can I silence the above compilation error?

Upvotes: 4

Views: 1887

Answers (2)

Martin R
Martin R

Reputation: 539965

You have to 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){
    }
}

The above code compiles with Swift 1.2 (Xcode 6.3) which added support for static computed properties. In earlier versions, you can define a nested struct containing the property as a workaround (compare 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){
    }
}

Upvotes: 5

giorashc
giorashc

Reputation: 13713

Since primaryColor is an instance variable it cannot be accessed until an instance is created from this class and since the function is part of the class definition you will get this error as primaryColor cannot access at that time.

You can either use MartinR approach or use your approach with the desired color:

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
    }

Upvotes: 1

Related Questions