swift - 使用 Swift 将默认值添加到输入参数

标签 swift function default-value swift3 inout

在 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

最佳答案

您所说的两个关键字,inoutvar,是非常不同的。

Apple Documentation 开始:

In-out parameters are passed as follows:

  1. When the function is called, the value of the argument is copied.
  2. In the body of the function, the copy is modified.
  3. 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/

相关文章:

ios - 导航栏标题

Swift:锁匠不更新数据

swift - 无法更改 FBSDKLoginButton 位置

function - 如何在 Mathematica 和 Matlab 中查找已定义符号的类型和内存位置?

django - 如何为自定义 Django 设置定义默认值

c# - XMLSerializer 为什么要取基类的 DefaultValue 属性来序列化

Swift - 添加一个覆盖现有导航栏的导航栏

javascript - 函数运行过程中出现奇怪的错误

ios - 调用函数并在展开可选值时意外发现 nil

c++ - 使用带有函数指针的 Wrapper 来处理参数的默认值