Swift Generics - Which method is called?

时间:2016-02-12 21:33:30

标签: swift generics

Assume the following toy example:

i = -5;
i > ( i - 8) :  -5 > (-5 -8 = -13) (always true) 
(i - 8) > -1 :  -13 > -1           (false) always false for i <= 7

If I have an array of 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 } } s - String - and I call [ "Foo", "Bar", "Baz" ] on it, which implementation will be called? Why?

I believe this is determined at compile time; in other words it's not a dynamic dispatch. But how is it determined? It feels like it would be similar to the rules around protocol extensions, but that's a dynamic dispatch situation...

1 个答案:

答案 0 :(得分:5)

It yields a

error: ambiguous use of 'doThing()'

Using the simply modified example:

     fw.write("Number of files processed within 512\u00B1 1 samples:  "+str(count))

The compiler complains

error: ambiguous use of 'doThing()'

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

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

The compiler simply does not know which one to call since the two methods have identical name and parameters.

Having multiple methods named the same but not actually related always poses the risk of some compiler problems when the two eventually overlap at some point.