Swift Generics - Which method is called?

Suppose the following toy example:

protocol AwesomeType: Equatable { var thingy: Int { get } } extension Array where Element: Equatable { func doThing { ... } } extension Array where Element: AwesomeType { func doThing { ... } } extension String: AwesomeType { var thingy: Int { return 42 } } 

If I have an array of String - [ "Foo", "Bar", "Baz" ] - and I call doThing() on it, which implementation will be called? Why?

I believe this is determined at compile time; in other words, this is not dynamic dispatch. But how is this determined? It looks like it will be like the rules around protocol extensions, but this is a dynamic sending situation ...

+5
source share
1 answer

This gives

error: ambiguous use of 'doThing ()'

Using a simple modified example:

 protocol AwesomeType: Equatable { } extension Array where Element: Equatable { func doThing() { print("array one") } } extension Array where Element: AwesomeType { func doThing() { print("array two") } } extension String: AwesomeType { } let arr = [ "Foo", "Bar", "Baz" ] arr.doThing() 

The compiler complains

error: ambiguous use of 'doThing ()'

Note: this candidate found
func doThing () {print ("array one")}

Note: this candidate found
func doThing () {print ("array two")}

The compiler simply does not know which call to call, because the two methods have the same name and parameters.

Having multiple methods with the same but unrelated methods always jeopardizes some problems with the compiler when they eventually overlap at some point.

+5
source

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


All Articles