为函数的参数分配默认值的困难 [英] Difficulties to assign default value to a parameter of a function

查看:32
本文介绍了为函数的参数分配默认值的困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但我收到编译器错误:不能使用实例成员DefaultValue"作为默认参数.

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

然后,我也尝试将 DefaultValue 声明为 private static:

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

但我收到新的编译器错误:Static let 'DefaultValue' 是私有的,不能从默认参数值中引用

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

我需要将 DefaultValue 私有 保留给这个类 &我想为带有私有变量的函数参数分配默认值,这在 Swift 4 中是否可以实现?

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?

推荐答案

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

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.

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

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
        // ...
    }
}

这篇关于为函数的参数分配默认值的困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆