有没有办法使用具有相同名称但返回类型不同的函数?

Rai*_*ann 3 methods declaration function swift

我的意图如下:

我的第一个功能:

public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String
Run Code Online (Sandbox Code Playgroud)

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

而我的第二个:

public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> Void
Run Code Online (Sandbox Code Playgroud)

只是为了修改某些东西

我知道需要不同的功能签名,但还有更好的方法吗?

JTe*_*eam 8

您可以使用两个具有相同名称,相同参数和不同返回类型的函数.但是如果你调用那个函数并且没有提供编译器调用哪个函数的任何线索,那么它会产生歧义错误,

例子:

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()'
Run Code Online (Sandbox Code Playgroud)

  • 这应该被认为是有效的答案。函数签名还包括返回类型。 (2认同)

das*_*ght 3

您无法定义两个具有相同参数类型的函数而不产生歧义,但您可以像调用返回值一样调用函数Void。这会生成一个警告,您可以通过将函数结果指定为可丢弃来消除该警告:

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