Default associatedType using protocol extension
Asked Answered
R

2

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.

Reuven answered 28/5, 2016 at 7:22 Comment(0)
B
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)

Bluebell answered 27/6, 2018 at 21:59 Comment(0)
T
-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
}
Thyrse answered 28/5, 2016 at 9:22 Comment(2)
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.Reuven
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.Reuven

© 2022 - 2024 — McMap. All rights reserved.