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

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

概述我习惯使用扩展在协议内部使用默认参数,因为协议声明本身不能使用它们,如下所示: protocol Controller { func fetch(forPredicate predicate: NSPredicate?)}extension Controller { func fetch(forPredicate predicate: NSPredicate? = 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 {        ...    }    //.....}

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

class SomeClassDatabaseController: SomeSpecificdatabaseControllerProtocol,DatabaseControllerProtocol {...}

我错过了什么?

解决方法 这种情况正在发生,因为编译器由于模糊的功能而混淆.

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

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

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

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}

@H_403_88@ 总结

以上是内存溢出为你收集整理的swift – 使用添加默认参数的方法扩展协议全部内容,希望文章能够帮你解决swift – 使用添加默认参数的方法扩展协议所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1016850.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-23
下一篇2022-05-23

发表评论

登录后才能评论

评论列表(0条)

    保存