gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:27:02 25 4
gpt4 key购买 nike

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

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
}

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

最佳答案

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

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

关于Swift:使用成员常量作为函数参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com