我曾经使用扩展在协议内部使用默认参数,因为协议声明本身不具备它们,如下所示:
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
我错过了什么?
答案 0 :(得分:2)
这种情况正在发生,因为编译器因功能模糊而混淆。
此处
SomeClassDatabaseController
从两个不同的协议接收count()
方法。
DatabaseControllerProtocol
有count(forPredicate)
方法,总是需要参数。另一方面
SomeSpecificDatabaseControllerProtocol
有count()
方法可以有空参数。- 醇>
要解决此问题,您必须将
DatabaseControllerProtocol
中的计数方法更改为此,或者您必须在SomeClassDatabaseController
中实施。
func count(forPredicate predicate: NSPredicate? = nil) -> Int { return 0}