难以将默认值分配给函数的参数

Lee*_*eem 8 swift swift4

在一个类中,我定义了一个私有常量,我尝试使用常量作为函数参数的默认值:

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) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

但我收到编译器错误: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) {
        ...
      }
    }
Run Code Online (Sandbox Code Playgroud)

但是我得到了新的编译错误: Static let 'DefaultValue' is private and cannot be referenced from a default argument value

我需要保持DefaultValue 私有这个类我想用私有变量为函数的参数赋值,是否可以在Swift 4中实现?

Mar*_*n R 8

我不认为这是可能的.默认值是在调用站点插入的,因此需要公开,另请参阅 swift 4中的访问控制.

可能的解决方法是使参数可选,并nil在本地替换默认值:

class Foo {
    private static let DefaultValue = 10

    public func doTask(amount: Int? = nil) {
        let amount = amount ?? Foo.DefaultValue
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)