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

标签 swift function methods declaration

我的意图如下:

我的第一个函数:

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/

相关文章:

javascript - 有没有标准的javascript函数可以将字符串转换为电话号码格式,反之亦然?

javascript - 我在 javascript 中有一个低温数组,我需要获得最低温度,所以我使用了 min.math 函数

swift - 在数据显示之前等待 1-2 秒从 Firebase 获取数据 (IOS)

ios - 通过 ios 应用程序 (swift) 将 URL 共享到 facebook 后无法获得结果帖子 ID

swift - 防止力量下降

c - C 函数的问题,特别是计算方面的问题

c# - 返回引用与不返回任何内容之间的区别

java - 调用静态方法时是否需要调用单独的方法?

java - 如何从 static void 方法返回 int 数据到 main 方法?

ios - JSON 到多维数组