swift - 在 Swift 中,当协议(protocol)被限制为从类继承时会发生什么?

标签 swift protocols swift-protocols

首先:错误代码:

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) Actionmethod1() 提供默认实现。

以下是没有意义的:

protocol Action where Self: AA {
   func method1()
   func method2()
}

您不能更改特定类的协议(protocol)。

关于swift - 在 Swift 中,当协议(protocol)被限制为从类继承时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868206/

相关文章:

swift - 如何从 NSObject 数组中过滤项目

swift - 从 Observable 中只获取一个值

objective-c - 多个协议(protocol)中的相同方法应该做什么? ( objective-c )

swift - 协议(protocol)扩展中的 'where self' 是什么

具有关联类型和影子类型删除的 Swift 协议(protocol)

swift - 我可以通过对这些协议(protocol)的扩展将协议(protocol)一致性添加到 `UnsignedInteger` 吗?

ios - UITableView 平滑滚动

ios - 如何使用事件 channel 将数据从 swift 流式传输到 flutter?

clojure - clojure协议(protocol)的简单解释

swift - 将一个协议(protocol)转换为另一个协议(protocol) Swift