Search code examples
swiftfunction-parameter

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?


Solution

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