Search code examples
swiftswift4

Difficulties to assign default value to a parameter of a function


In a class, I defined a private constant, I try to use the constant as a default value of parameter of a function:

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) {
    ...
  }
}

But I get compiler error: Cannot use instance member 'DefaultValue' as a default parameter.

Then, I also tried declare DefaultValue as 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) {
        ...
      }
    }

But I get new compiler error: Static let 'DefaultValue' is private and cannot be referenced from a default argument value

I need to keep DefaultValue private to this class & I would like to assign default value to the parameter of function with a private variable, whether this is achievable in Swift 4?


Solution

  • I don't think that is possible. The default value is inserted at the calling site, and therefore needs to be public, see also Access control in swift 4.

    A possible workaround would be to make the parameter optional, and substitute nil by the default value locally:

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