Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default associatedType using protocol extension

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.

like image 513
Ayush Goel Avatar asked May 28 '16 07:05

Ayush Goel


People also ask

What is protocol extension?

Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.

Can we use extension for protocol types?

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don't have access to the original source code (known as retroactive modeling).

What is associated type?

What is an associated type? An associated type can be seen as a replacement of a specific type within a protocol definition. In other words: it's a placeholder name of a type to use until the protocol is adopted and the exact type is specified. This is best explained by a simple code example.

Can only be used as a generic constraint because it has self or associated type requirements?

Protocol 'SomeProtocol' can only be used as a generic constraint because it has Self or associated type requirements. Code that uses a protocol that relies on associated types pays the price. Such code must be written using generic types. Generic types are also placeholders.


1 Answers

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)

like image 190
Guillaume Algis Avatar answered Oct 05 '22 10:10

Guillaume Algis