A question about associatedtype in protocols

associatedtype
protocol

(Roy Hsu) #1

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.


(Anthony Latsis) #2

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
}


(Roy Hsu) #3

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.


(Jacob Williams) #4

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.


(Jordan Rose) #5

cc @nnnnnnnn


(Anthony Latsis) #6

We're probably going to support the "proper" way - using type aliases in protocol extensions - if https://github.com/apple/swift-evolution/pull/857 gets accepted. This would also enable customization of default values for associated types in constrained extensions.


(Nate Cook) #7

Good find! Filed SR-8761.