首先:错误代码:
class AA { }
protocol Action where Self: AA {
func method1()
func method2()
}
extension Action {
func method1() {
print("method1")
}
}
class List: AA, Action {
func method2() {
print("List method2")
}
}
class Detail: AA, Action {
func method2() {
print("Detail method2")
}
}
let controllers = [List(), Detail()] as [Any]
if let action = controllers.first as? Action {
action.method2() //error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x2).
}
然后正确的代码,一切正常:
protocol Action {
func method1()
func method2()
}
extension Action where Self: AA {
func method1() {
print("method1")
}
}
问题一: 当协议(protocol)被限制为从类继承时会发生什么?
问题2: 正确的代码和错误的代码有什么区别?
最佳答案
协议(protocol)不能从类继承。
但是,如果实现类符合某些条件,您可以为协议(protocol)方法提供默认实现。 where
子句定义了此类条件。
这段代码:
extension Action where Self: AA {
func method1() {
print("method1")
}
}
为 AA
类中的协议(protocol) Action
的 method1()
提供默认实现。
以下是没有意义的:
protocol Action where Self: AA {
func method1()
func method2()
}
您不能更改特定类的协议(protocol)。
关于swift - 在 Swift 中,当协议(protocol)被限制为从类继承时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868206/