Let's assume I've a protocol Foo with an associatedtype Bar. Is there any way to use this same associatedtype as a constraint in a generic function inside this same protocol?
To illustrate:
protocol Foo { associatedtype Bar func example<T: Bar>() -> T } This will throw a Inheritance from non-protocol, non-class type 'Self.Bar'. Which makes total sense, because at compile-time, we don't know which type Bar will be.
Nonetheless, for some reason, even if I define the Bar type, I will still get the same error. Something like this:
protocol Foo { associatedtype Bar: NSObject //OR: Protocol func example<T: Bar>() -> T //Compile Error: Inheritance from non-protocol, non-class type 'Self.Bar' } Both this and this questions address the same issue, but none of them are real answers in my honest opinion.
Also, maybe I'm approaching this in a wrong perspective of the language, but to visualize my use case: I need that when the class defines the type of Bar, each T used in example() function, should be a Bar type, but knowing which type it will return. To illustrate what would be my state of art:
protocol Foo { associatedtype Bar: NSObject //OR: Protocol //Compile Error: Inheritance from non-protocol, non-class type 'Self.Bar' func example<T: Bar>() -> T //OR: func example<T>() -> T where T: Bar } class ExampleBarType: NSObject { } class ExampleObject: ExampleBarType { } class FooImplementation: Foo { typealias Bar = ExampleBarType func example<T: Bar>() -> T { //OR: func example<T>() -> T where T: Bar { } } I just can't seem to grasp why the compiler can't assume that my associatedtype will be the one that I've defined. Thanks in advance.