Extending a protocol using a method that adds a default parameter

I use the default parameters inside protocols using extensions, since the protocol declarations themselves cannot be like this:

protocol Controller { func fetch(forPredicate predicate: NSPredicate?) } extension Controller { func fetch(forPredicate predicate: NSPredicate? = nil) { return fetch(forPredicate: nil) } } 

Worked great for me.

Now I have the following situation: I have one specific protocol for a certain type of controller:

 protocol SomeSpecificDatabaseControllerProtocol { //... func count(forPredicate predicate: NSPredicate?) -> Int } 

And the extension of the protocol with the implementation of standard methods for controllers:

 protocol DatabaseControllerProtocol { associatedtype Entity: NSManagedObject func defaultFetchRequest() -> NSFetchRequest<Entity> var context: NSManagedObjectContext { get } } extension DatabaseControllerProtocol { func save() { ... } func get() -> [Entity] { ... } func count(forPredicate predicate: NSPredicate?) -> Int { ... } //..... } 

My problem is that when I try to add a method with a default parameter to the SomeSpecificDatabaseControllerProtocol extension, I get a compile-time error that the specific class corresponding to SomeSpecificDatabaseControllerProtocol does not match the protocol (only happens if I extend the protocol):

 class SomeClassDatabaseController: SomeSpecificDatabaseControllerProtocol, DatabaseControllerProtocol {...} 

What am I missing?

+5
source share
1 answer

This is because the compiler is confused due to ambiguous functions.

  • Here is SomeClassDatabaseController receiving the count() method from two different protocols.

  • DatabaseControllerProtocol has a count(forPredicate) method that always needs a parameter.

  • On the other hand, SomeSpecificDatabaseControllerProtocol has a count() method that can have an empty parameter.

  • To solve this problem, you need to change the counting method in DatabaseControllerProtocol , or you must implement it in SomeClassDatabaseController .

func count(forPredicate predicate: NSPredicate? = nil) -> Int { return 0}

+2
source

Source: https://habr.com/ru/post/1274655/


All Articles