Fast protocol extension that implements another protocol with a common associated type

Consider the following:

protocol Foo { typealias A func hello() -> A } protocol FooBar: Foo { func hi() -> A } extension FooBar { func hello() -> A { return hi() } } class FooBarClass: FooBar { typealias A = String func hi() -> String { return "hello world" } } 

This code compiles. But if I comment on the explicit definition of the associated type, typealias A = String , then for some reason swiftc will not be able to infer the type.

I believe that this is due to two protocols using the same bound type , but without direct assertion through, for example, type parameterization (maybe the bound type is not powerful / mature enough?), Which makes it ambiguous for type inference.

I'm not sure if this is a language error / immaturity, or maybe I miss some nuances in the protocol extension that rightfully lead to this behavior.

Can someone shed some light on this?

+6
source share
2 answers

look at this example

 protocol Foo { typealias A func hello() -> A } protocol FooBar: Foo { typealias B func hi() -> B } extension FooBar { func hello() -> B { return hi() } } class FooBarClass: FooBar { //typealias A = String func hi() -> String { return "hello world" } } 

with generics

 class FooBarClass<T>: FooBar { var t: T? func hi() -> T? { return t } } let fbc: FooBarClass<Int> = FooBarClass() fbc.t = 10 fbc.hello() // 10 fbc.hi() // 10 
+1
source

Providing explicit values ​​for related types in the protocol is required to comply with the specified protocol. This can be done using hard type encoding, as was done with typealias A = String , or using a parameterized type, as you mentioned below:

 class FooBarClass<T>: FooBar { typealias A = T ... } 

Swift will not call your bound type from the implemented protocol method, as there may be ambiguity with several methods with inappropriate types. This is why typealias must be explicitly allowed in your implementation class.

0
source

All Articles