微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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. Here SomeClassDatabaseController receiving count() method from two different protocols.

  2. DatabaseControllerProtocol has count(forPredicate) method which always need parameter.

  3. On other hand SomeSpecificDatabaseControllerProtocol have count() method which can have empty parameter.

  4. To solve this either you have to change count method in DatabaseControllerProtocol to this or you have to implement it in SomeClassDatabaseController.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐