Swift: using member constant as default value for function parameter

旧巷老猫 提交于 2021-01-27 07:08:15

问题


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?


回答1:


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



回答2:


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
    }


来源:https://stackoverflow.com/questions/29730452/swift-using-member-constant-as-default-value-for-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!