swift - 难以为函数的参数分配默认值
问题描述
在一个类中,我定义了一个私有常量,我尝试使用该常量作为函数参数的默认值:
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
为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
私有并且我想用一个私有变量为函数的参数分配默认值,这在 Swift 4 中是否可以实现?
解决方案
我不认为这是可能的。默认值是在调用站点插入的,因此需要公开,另请参见 swift 4 中的访问控制。
一种可能的解决方法是使参数可选,并nil
在本地替换为默认值:
class Foo {
private static let DefaultValue = 10
public func doTask(amount: Int? = nil) {
let amount = amount ?? Foo.DefaultValue
// ...
}
}
推荐阅读
- swift - Swift4 Decodable - 将一半的键解码为字典
- firebase - firebase_analytics:CocoaPods 找不到 pod“Firebase/Core”的兼容版本
- python - CSRF 令牌丢失或不正确。带烧瓶
- java - 如何解析获取请求响应?
- php - sql 限制 current_date 时间戳
- javascript - WordPress 中的“添加自定义 HTML”块完美地预览了我的代码,但是当我回来时,一切都搞砸了
- python-3.x - 我怎样才能让这些功能在我的菜单中工作
- javascript - 无法安装@adonijs/mail
- rust - 如何观察 Rust 的变化?
- dynamics-crm - Dynamics CRM 错误:关于业务流程和相关工作流程