【问题标题】:Why doesn't type inference come to the rescue in the case of a swift function with multiple uniquely typed default parameters?在具有多个唯一类型默认参数的 swift 函数的情况下,为什么类型推断不能发挥作用?
【发布时间】:2017-10-10 01:54:46
【问题描述】:

考虑以下方法签名:

func doSomething(_ boolToConsider: Bool = false, _ stringToConsider: String? = nil)

按以下方式调用该方法会报错:

doSomething("foo")

为什么 Swift 不承认我打算使用默认的 boolToConsider 和提供的 stringToConsider

【问题讨论】:

  • 您是否尝试过使用函数参数的外部名称?你也可以使用两个函数,一个接收布尔值,第二个接收字符串,然后创建第三个函数来为两者做一些共同的事情

标签: swift type-inference overloading default-parameters


【解决方案1】:

正如@Woof 已经提到的,您可以提供 3 个不同的方法签名来完成您想要的事情,并且只有其中一个可以将所有参数设置为默认值,否则它会抱怨您的方法使用不明确:

func doSomething(_ bool: Bool) {
    print("bool:", bool)
}
func doSomething(_ string: String) {
    print("string:", string)
}
func doSomething(_ bool: Bool = false, _ string: String = "") {
    print("bool:", bool)
    print("string:", string)
}

doSomething(true)
doSomething("foo")
doSomething()
doSomething(true, "foo")

这将打印出来

doSomething 仅具有布尔值

布尔:真

doSomething 只包含字符串值

字符串:foo

使用默认值做某事

布尔:假

字符串:默认

使用默认值做某事

布尔:真

字符串:foo

【讨论】:

    【解决方案2】:

    我不知道为什么 Swift 的作者不支持它,或者他们是否打算支持它。我可以推测,基于类型推断参数列表的哪些部分被传递会导致相当混乱的代码。

    你可以重载你的函数。

    func doSomething(_ stringToConsider: String) {
      doSomething(false, stringToConsider)
    }
    

    【讨论】:

      【解决方案3】:

      类型推断不适用于您的示例,因为您的所有外部参数标签都是匿名 (_)。给doSomething 至少一个参数标签可以解决这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 2018-05-15
        相关资源
        最近更新 更多