6

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.

Ayush Goel
  • 3,134
  • 27
  • 36

2 Answers2

1

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)

Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
-1

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
}
Khundragpan
  • 1,952
  • 1
  • 14
  • 22
  • 1
    This is exactly what I don't want to do. I want my class to just conform to a protocol and get the default implementation based on what type it is. – Ayush Goel May 28 '16 at 14:47
  • By the way, you can simply say `func fooFunction(bar: Bar) {}` in your protocol implementation. It would automatically pick the conforming class's associated type. No need for `SomeClass.Bar`. – Ayush Goel May 28 '16 at 14:47