6
votes

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.

2

2 Answers

1
votes

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)

-1
votes

There are two associatedtype Bar available in extension context and compiler cannot deduce the correct one. Try this.

protocol Foo: class {
  associatedtype Bar
  func fooFunction(bar: Bar)
}

extension Foo where Self: SomeClass {
  func fooFunction(bar: SomeClass.Bar) {}
}

class SomeClass:Foo{
  typealias Bar = Int
}