在一个类中,我定义了一个私有常量,我尝试使用该常量作为函数参数的默认值:
class Foo {
// instance variable
private let DefaultValue = 10
// Compiler error: Cannot use instance member 'DefaultValue' as a default parameter
public func doTask(amount: Int = DefaultValue) {
...
}
}
但我收到编译器错误:Cannot use instance member 'DefaultValue' as a default parameter
.
然后,我也尝试声明DefaultValue
as private static
:
class Foo {
// static variable
private static let DefaultValue = 10
// Compiler error: Static let 'DefaultValue' is private and cannot be referenced from a default argument value
public func doTask(amount: Int = DefaultValue) {
...
}
}
但我收到新的编译器错误:Static let 'DefaultValue' is private and cannot be referenced from a default argument value
我需要保留DefaultValue
private对于此类,我想使用私有变量为函数的参数分配默认值,这在 Swift 4 中是否可以实现?
我认为这是不可能的。默认值是在调用站点插入的,因此需要公开,另请参阅Swift 4 中的访问控制.
一个可能的解决方法是使参数可选,
并替代nil
本地默认值:
class Foo {
private static let DefaultValue = 10
public func doTask(amount: Int? = nil) {
let amount = amount ?? Foo.DefaultValue
// ...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)