【问题标题】:Is there a way to use functions with same names but different return types?有没有办法使用名称相同但返回类型不同的函数?
【发布时间】:2017-06-17 11:04:27
【问题描述】:

我的意图如下:

我的第一个功能:

public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String

例如,我可以在print() 的上下文中使用它。

我的第二个:

public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> Void

只是为了修改一些东西。

我知道需要不同的函数签名,但有没有更好的方法?

【问题讨论】:

  • 否,但您可以使用返回 String 的函数,就好像它是 Void
  • 听起来很完美。我怎样才能意识到这一点?
  • 只调用它,不要将结果分配给任何变量。 Swift 会让你这么做。
  • 但随后出现警告:“调用...的结果未使用”。
  • 您还需要将其标记为@discardableResult 以指示不必使用返回值(比较Result of call to [myFunction] is unused)。但我不建议使用同时返回变异实例的mutating 方法——如果在单独的行上调用该方法,然后再使用变异实例,则该方法的用法会更清晰。否则,乍一看,该方法可能会创建一个新字符串,而不是变异。

标签: swift function methods declaration


【解决方案1】:

您可以拥有两个具有相同名称、相同参数和不同返回类型的函数。但是如果你调用那个函数并且没有提供任何线索告诉编译器调用这两个函数中的哪个函数,那么它就会给出歧义错误,

例子:

func a() -> String {
    return "a"
}

func a() -> Void {
    print("test")
}


var s: String;
s = a()
// here the output of a is getting fetched to a variable of type string,
// and hence compiler understands you want to call a() which returns string

var d: Void = a() // this will call a which returns void

a() // this will give error Ambiguous use of 'a()'

【讨论】:

  • 这应该被认为是有效的答案。函数签名也包括返回类型。
【解决方案2】:

您不能在不产生歧义的情况下定义具有相同参数类型的两个函数,但您可以调用返回值的函数,就好像它是Void。这会生成一个警告,您可以通过将函数结果指定为可丢弃来使其静音:

@discardableResult
public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String {
}

【讨论】:

  • 就是这样。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
相关资源
最近更新 更多