What are the Swift overload resolution rules for both functions and operators?

How does the Swift 2.1 compiler determine which method or statement is invoked based on the set of overloads on this site?

This issue may combine two problems: method overloads and operator overloads, but it seems, at least superficially, that they are related. For some reason, they end up using different rules, as I will demonstrate in the near future.

class A{ } class B: A { } func +(a:A, b:A){ print("+1") } func +(a:A, b:B){ print("+2") } func +(a:B, b:A){ print("+3") } /* func +(a:B, b:B){ print("+4") } */ A() + A() // prints +1 A() + B() // prints +1 B() + A() // prints +1 // B() + B() // will come back to this func f(a: A, b: A){ print("f1") } func f(a: B, b: A){ print("f2") } func f(a: A, b: B){ print("f3") } /* func f(a: B, b: B){ print("f4") } */ f(A(), b: A()) // prints f1 f(B(), b: A()) // prints f2 f(A(), b: B()) // prints f3 // f(B(), b: B()) // will come back to this 

Deriving from various calls to f() makes sense. It seems that Swift uses similar overload resolution rules like Java, where the "most specific method" is selected, given the set of methods whose parameters are part of the same class hierarchy.

Given the as-is code, the outputs from operator overloading all seem to call the first operator defined. The order of definition does not matter if +(A, A) is placed last, it will still be called by all three calls of +. It doesn't make sense to me anymore. Why doesn't +(A, B) invoke the expression A() + B() ?

Something strange happens when the function +(B, B) uncommented. Suddenly, overloads work the same way as with the usual function definition.

Full code:

 func +(a:A, b:A){ print("+1") } func +(a:A, b:B){ print("+2") } func +(a:B, b:A){ print("+3") } func +(a:B, b:B){ print("+4") } A() + A() // prints +1 A() + B() // prints +2 B() + A() // prints +3 B() + B() // prints +4 

Without the definition of +(B, B) expression B() + B() is an error because it is ambiguous to choose +(A, B) or +(B, A) . I am fine with this behavior. But why do A()+B() and B()+A() suddenly relate to the operators +2 and +3 respectively?

The regular case of a function does not behave this way. Given the 3 uncommented definitions of f , as indicated above, the output will be as expected, f1 , f2 , f3 in order. If the definition of f(B, B) not satisfied, the expression f(B(), B()) works as expected and prints f4 . Other expressions are not affected.

+5
source share

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


All Articles