【发布时间】:2018-01-12 17:52:01
【问题描述】:
我习惯于在使用扩展的协议中使用默认参数,因为协议声明本身不能拥有它们,如下所示:
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 {...}
我错过了什么?
【问题讨论】:
标签: swift swift-protocols swift-extensions