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

时间:2018-01-12 09:18:26

标签: swift swift-protocols swift-extensions

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

 namesSorted = names; // names is my list to be sorted i am taking it to nnnew array namessorted
    Collections.sort(namesSorted, new Comparator<MatchModel>() {
        @Override
        public int compare(MatchModel o1, MatchModel o2) {
            return o1.getTimestamp().compareTo(o2.getTimestamp());
        }
    });

完美地为我工作。

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

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

我错过了什么?

1 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为编译器因功能模糊而混淆。

  
      
  1. 此处SomeClassDatabaseController从两个不同的协议接收count()方法。

  2.   
  3. DatabaseControllerProtocolcount(forPredicate)方法,总是需要参数。

  4.   
  5. 另一方面SomeSpecificDatabaseControllerProtocolcount()方法可以有空参数。

  6.   
  7. 要解决此问题,您必须将DatabaseControllerProtocol中的计数方法更改为此,或者您必须在SomeClassDatabaseController中实施。

  8.         

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