2017-06-17 53 views
2

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

我的第一功能:

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

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

我的第二个:

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

刚刚修改的东西。

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

+0

没有,但你可以使用函数返回'String'好像是'Void'。 – dasblinkenlight

+0

听起来很完美。我怎么能意识到这一点? –

+0

只需调用它,不要将结果分配给任何变量。斯威夫特会让你这样做。 – dasblinkenlight

回答

2

无法定义具有相同的参数类型两种功能不会产生歧义,但您可以调用返回值的函数,就好像它是Void。这会产生一个警告,您可以通过指定的函数的结果废弃的沉默:

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

就是这样。谢谢! –

4

您可以拥有两个具有相同名称,相同参数和不同返回类型的函数。但是,如果你调用该函数并没有提供任何线索编译两个函数来调用它,那么它给出模棱两可的错误,

例子:

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()' 
+1

这应该被认为是有效的答案。函数签名还包括返回类型。 – user3441734

相关问题