我的意图如下:
我的第一个函数:
public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> String
例如,我可以在 print()
的上下文中使用它。
我的第二个:
public mutating func replaceSubstringInRange(_ range: CountableClosedRange<Int>, withString string: String) -> Void
只是为了修改一些东西。
我知道需要不同的函数签名,但有没有更好的方法?
最佳答案
您可以拥有两个具有相同名称、相同参数和不同返回类型的函数。但是如果你调用那个函数并且没有向编译器提供任何线索来调用这两个函数中的哪个函数,那么它会给出歧义错误,
例子:
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()'
关于swift - 有没有办法使用名称相同但返回类型不同的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603840/