Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use functions with same names but different return types?

My intention is the following:

My first function:

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

that I can use it in a context of print() for example.

And my second:

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

just for modifying something.

I know that there is a different function signature needed, but is there any better way?

like image 279
Rainer Niemann Avatar asked Dec 06 '22 14:12

Rainer Niemann


1 Answers

You can have two functions with same name, same parameters and different return type. But if you call that function and do not provide any clue to compiler which function of the two to call, then it gives ambiguity error,

Examples:

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()'
like image 105
JTeam Avatar answered Dec 08 '22 03:12

JTeam