首页 > 解决方案 > 难以为函数的参数分配默认值

问题描述

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

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.

然后,我也尝试声明DefaultValueprivate 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 中是否可以实现?

标签: swiftswift4

解决方案


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

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

class Foo {
    private static let DefaultValue = 10

    public func doTask(amount: Int? = nil) {
        let amount = amount ?? Foo.DefaultValue
        // ...
    }
}

推荐阅读