I have a protocol with an associatedType
.
I want to give a default typealias
for that type in the protocol extension. This is to be done only for classes that inherit from a particular class.
protocol Foo: class {
associatedtype Bar
func fooFunction(bar: Bar)
}
Protocol extension:
extension Foo where Self: SomeClass {
typealias Bar = Int
func fooFunction(bar: Int) {
// Implementation
}
}
The compiler complains that 'Bar' is ambiguous for type lookup in this context
. I was unable to find anything helpful in swift book too.
Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don't have access to the original source code (known as retroactive modeling).
What is an associated type? An associated type can be seen as a replacement of a specific type within a protocol definition. In other words: it's a placeholder name of a type to use until the protocol is adopted and the exact type is specified. This is best explained by a simple code example.
Protocol 'SomeProtocol' can only be used as a generic constraint because it has Self or associated type requirements. Code that uses a protocol that relies on associated types pays the price. Such code must be written using generic types. Generic types are also placeholders.
Just had the same problem, and with Swift 4 (maybe in earlier version too, I haven't tested), you can just add a default for your associatedtype
in its definition:
protocol Foo: class {
associatedtype Bar = Int // notice the "= Int" here
func fooFunction(bar: Bar)
}
No need to add an extension to your protocol for that.
(I could not find any mention of this in the doc, but it worked as expected for me and seems natural to write it that way. If you can link to some reputable source, please feel free to edit it in the answer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With