考虑以下示例:
class ManObj {
func baseFunc() {
print("ManObj baseFunc")
}
}
class SubObj: ManObj {
}
protocol Model {
}
extension Model { // This is protocol extension
func someFunc() { // Protocol extension default implementation
(self as! ManObj).baseFunc()
print("Model implementation")
}
}
extension SubObj: Model {
func someFunc() {
print("SubObj Implementation")
}
}
let list = SubObj()
list.someFunc() // static dispatching
let list2: Model = SubObj()
list2.someFunc() // dynamic dispatching
输出很好:
SubObj Implementation
ManObj baseFunc
Model implementation
但我不喜欢排队的演员(self as! ManObj).baseFunc()。
事实上,我只打算将Model协议应用于ManObj. (但并非所有的子类ManObj都是Model!)所以,我尝试更改Model为:
extension Model where Self: ManObj {
func someFunc() {
self.baseFunc() // No more casting needed!
print("Model implementation")
}
}
但我遇到了错误:
list2.someFunc()<-error: 'Model' is not a subtype of 'ManObj'
那么,有没有办法让我在我约束Model.someFunc到之后触发?list2Modelwhere Self: ManObj