0

考虑以下示例:

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

4

1 回答 1

0

创建一个空类仅用于类型转换

class ManObj {
    func baseFunc() {
        print("ManObj baseFunc")
    }
}

class SubObj: ModelCaster {
    func someFunc() {
        print("SubObj Implementation")
    }
}

protocol Model {
}

extension Model where Self: ModelCaster { // This is protocol extension
    func someFunc() { // Protocol extension default implementation
        print("Model implementation")
    }
}

class ModelCaster: ManObj, Model{

}

let list = SubObj()
list.someFunc() //SubObj Implementation

let list2: ModelCaster = SubObj()
list2.someFunc() //Model implementation
于 2017-03-21T13:31:17.557 回答