在 Swift 2 中,可以执行以下操作:
class SomeType {
static let singletonInstance = SomeType()
func someFunction(var mutableParameter: SomeType = SomeType.singletonInstance) {
...
}
}
但是在 Swift 3 中,函数参数的 var
关键字将被移除,取而代之的是 inout
。我无法使用 inout
关键字获得与上述相同的结果。
class SomeType {
static let singletonInstance = SomeType()
func someFunction(inout mutableParameter: SomeType = SomeType.singletonInstance) {
...
}
}
相反,我收到错误消息“类型‘SomeType’的默认参数值无法转换为类型‘inout SomeType’”
我的问题是是否可以使用默认值的inout
?
最佳答案
您所说的两个关键字,inout
和 var
,是非常不同的。
从 Apple Documentation 开始:
In-out
parameters are passed as follows:
- When the function is called, the value of the argument is copied.
- In the body of the function, the copy is modified.
- When the function returns, the copy’s value is assigned to the original argument.
因此,您不能为 inout
参数指定默认值,因为这会使 inout
属性完全无用。
你可以做的是接收一个普通的(常量)参数和一个默认值,并用这种方式声明一个同名的新var
(代码来自Swift Evolution's Removing var from Function Parameters Proposal , 添加默认参数):
func foo(i: Int = 5) {
var i = i
// now you can change i as you'd like
}
关于swift - 使用 Swift 将默认值添加到输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245597/