Search code examples
swiftgenericstype-constraintsgeneric-function

swift generic func with overlapping type constraints


I have this protocol hierarchy:

protocol A {}

protocol B: A {}

what will happen if I have the 2 following funcs:

func myFunc<T : A where T: B>( object: T){ ... }
func myfunc<T : A>( object: T){ ... }

Which function will be executed if I call

myFunc( object: myInstance ) 

with myInstance conforming to protocol B. In this case myInstance matches the 2 constraints.

Thanks


Solution

  • The general rule is that the compiler tries to select the most specific / most constrained overload.

    For your example above, it would be the first version of myFunc