Swift - Assigning Overloaded Function to Variable

后端 未结 5 542
走了就别回头了
走了就别回头了 2021-01-05 07:52

I am getting a compile time error that myFunc reference is ambiguous.

func f (s: String) -> String { return \"version 1: \" + s }
func f(sourceString s: S         


        
5条回答
  •  天涯浪人
    2021-01-05 08:18

    Interesting one this. I don’t think it’s possible without doing something along the lines of @marcos’s suggestion. The problem you is you can “cast away” 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, identical except one has named arguments:

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

    You can then call it via tuples with named vs unnamed arguments:

    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 because you can cast away 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 it’s not possible to use a type to disambiguate an function overloaded only by argument names, as far as I can tell.

提交回复
热议问题