Swift - Assigning an Overloaded Function to a Variable

I get a compile-time error that the myFunc link is ambiguous.

func f (s: String) -> String { return "version 1: " + s } func f(sourceString s: String) -> String { return "version 2: " + s } var myFunc: (String)-> String = f as (sourceString : String)->String 

How can I explicitly reference each version of an overloaded function, f, in the above example? If I comment on either the func f declaration, it will compile and work. But I would like to know how to reference each of the functions if they are declared. Thanks.

+6
source share
4 answers

I wonder what that is. I do not think it is possible without doing something as suggested by @marcoss. The problem is that you can drop the names in tuples:

 let named_pair = (s: "hello", i: 1) named_pair.s // hello let anon_pair = named_pair as (String,Int) // or anon_pair: (String,Int) = named_pair, if you prefer anon_pair.s // no such member 's' 

Now suppose you define two functions that are identical, except that one has named arguments:

 func f(s: String, i: Int) { println("_: \(s)") } func f(#s: String, #i: Int) { println("s: \(s)") } 

Then you can call it through tuples with named arguments vs unnamed:

 f(named_pair) // prints s: hello f(anon_pair) // prints _: hello // but if you try to call a named argument function with unnamed tuples: func g(# s: String, # i: Int) { println("s: \(s)") } g(anon_pair) // compiler error let h = g h(anon_pair) // compiler error h(named_pair) // works 

But since you can drop these names, you can do this:

 // compiles and runs just fine... (g as (String,Int)->())(anon_pair) let k: (String,Int)->() = g // as does this k(anon_pair) 

And this ability to do this means that you cannot use a type to disambiguate a function that is overloaded only with argument names, as far as I can tell.

+4
source

I don't know how to do exactly what you want, but maybe this helps:

 var myFunc1: (String)-> String = { s in f(sourceString: s) } var myFunc2: (String)-> String = { s in f(s) } 

Now you can call:

 let s1 = myFunc1("one") // returns "version 2: one" let s2 = myFunc2("two") // returns "version 1: two" 
+5
source
  • The number of arguments should be different.
  • If the number of arguments is the same, then their data types must be changed.

Example

  func f (x: String) -> NSString {
         return a
     }
 func f (x: UInt) -> NSString {
             return "{\ (x)}"
         }
+1
source

I do not think you can. You can call one or the other:

 println(f("test")) // version 1: test println(f(sourceString: "test")) // version 2: test 
0
source

Source: https://habr.com/ru/post/981887/


All Articles