我习惯使用扩展在协议内部使用默认参数,因为协议声明本身不能使用它们,如下所示:
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 回答
This is happening because compiler is confuse due to ambiguous functions.