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

Swift 使用添加默认参数的方法扩展协议,swift,swift-protocols,swift-extensions,Swift,Swift Protocols,Swift Extensions,我习惯于在使用扩展的协议中使用默认参数,因为协议声明本身不能使用这些参数,如下所示: protocol Controller { func fetch(forPredicate predicate: NSPredicate?) } extension Controller { func fetch(forPredicate predicate: NSPredicate? = nil) { return fetch(forPredicate: nil) } } 对

我习惯于在使用扩展的协议中使用默认参数,因为协议声明本身不能使用这些参数,如下所示:

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

    //.....
}

我遗漏了什么?

发生这种情况是因为编译器由于函数不明确而混淆。

  • 这里是来自两个不同协议的
    SomeClassDatabaseController
    接收
    count()
    方法

  • DatabaseControllerProtocol
    count(forPredicate)
    方法,它总是需要参数

  • 另一方面,
    SomeSpecificDatabaseControllerProtocol
    have
    count()
    方法可以有空参数

  • 要解决这个问题,您必须将
    DatabaseControllerProtocol
    中的count方法更改为this,或者必须在
    SomeClassDatabaseController
    中实现它

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


    是的,没错,这就是我刚才理解的:)最简单的方法是用
    DatabaseControllerProtocol
    声明更改func的接口有时我们需要更具体一些。我们不能总是依赖工具。或者必须指定它应该调用哪个类方法。
    class SomeClassDatabaseController: SomeSpecificDatabaseControllerProtocol, DatabaseControllerProtocol {...}