加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:58:09 所属栏目:百科 来源:网络整理
导读:我习惯使用扩展在协议内部使用默认参数,因为协议声明本身不能使用它们,如下所示: protocol Controller { func fetch(forPredicate predicate: NSPredicate?)}extension Controller { func fetch(forPredicate predicate: NSPredicate? = nil) { return fetc
我习惯使用扩展在协议内部使用默认参数,因为协议声明本身不能使用它们,如下所示:

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}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读