I have a question about associatedtype in protocols.
I'm not sure how they actually mean in the following example.
protocol Foo { }
protocol Bar {
// I have no problem with this.
associatedtype A: Foo
// What does this "=" mean? Is it like a typealias?
associatedtype B = Foo
// Does C equal to B?
typealias C = Foo
}
I expect it will show a compile error when I use "=" with an asscociatetype, but that doesn't happen...
I did some searching but found nothing.
So my question is if this is just another way to declare typealias in protocols?
This is how you define a default value for an associated type. In other words, if you don't implement B when conforming to Bar, B will be equal to Foo.
protocol Bar {
associatedtype B = Foo
}
class Class1: Bar {
func foo(arg: B) { ... } // B == Foo
}
class Class2: Bar {
typealias B = Int
func foo(arg: B) { ... } // B == Int
}
Thanks for your good explanation.
Now, I understand how it works.
I encountered this because of mistyping : with = when defining associated types.
It seems like that there is no official guide to help people learn this behavior.
Most online resources for protocols with associated types only explain associatedtype: Foo but associatedtype = Foo
Hope The Swift Programming Language ebook will add some explanation about this in the future.
Or it may not be an issue that needs to be well-documented for most people.
I agree that this is confusing behavior for newcomers. Especially considering how all other protocol default implementations must be contained in an extension of the protocol.
This should definitely be documented somewhere...I too was confused by this syntax at first.