A question about associatedtype in protocols

Hi, community

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?

Thanks.

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
}

2 Likes

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.

2 Likes

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.

1 Like

cc @nnnnnnnn

1 Like

We're probably going to support the "proper" way - using type aliases in protocol extensions - if Reconsider semantics of type aliases in protocol extensions by AnthonyLatsis · Pull Request #857 · apple/swift-evolution · GitHub gets accepted. This would also enable customization of default values for associated types in constrained extensions.

4 Likes

Good find! Filed SR-8761.

3 Likes