首页 文章

使用添加默认参数的方法扩展协议

提问于
浏览
5

我习惯使用扩展在协议内部使用默认参数,因为协议声明本身不能使用它们,如下所示:

protocol Controller {
   func fetch(forPredicate predicate: NSPredicate?)
}

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

为我工作完美 .

现在我有下一个情况,我有一个特定类型的控制器的特定协议:

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

和协议扩展以及控制器的默认方法的实现:

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 {
        ...
    }

    //.....
}

我的问题是当我尝试将带有默认参数的方法添加到 SomeSpecificDatabaseControllerProtocol 扩展名时,我收到编译时错误,符合 SomeSpecificDatabaseControllerProtocol 的具体类不符合协议(仅当我扩展协议时才会发生) :

class SomeClassDatabaseController: SomeSpecificDatabaseControllerProtocol, DatabaseControllerProtocol {...}

我错过了什么?

1 回答

  • 2

    This is happening because compiler is confuse due to ambiguous functions.

    这里SomeClassDatabaseController从两个不同的协议接收count()方法 . DatabaseControllerProtocol具有count(forPredicate)方法,它总是需要参数 . 另一方面,SomeSpecificDatabaseControllerProtocol有count()方法,它可以有空参数 . 要解决这个问题,您必须将DatabaseControllerProtocol中的count方法更改为this,或者您必须在SomeClassDatabaseController中实现它 . func count(forPredicate谓词:NSPredicate?= nil) - > Int {return 0}

相关问题