将一个协议转换为另一个协议 Swift

Cast a protocol to another protocol Swift

我正在尝试使用跨 Pods 的协议。 然后我在这里按问题进行了简化,这样我就可以在 Whosebug 上提问了。

在我的问题中,TestClass 对 SecondProtocol 一无所知(因为它位于单独的 pod 中)。

public protocol FirstProtocol {
    func get(data: String) -> String
}

public protocol SecondProtocol {
    func get(data: String) -> String
}

class TestClass {
    func get(data: String) -> String {
        return "Rest data"
    }

    public init() { }
}

extension TestClass : FirstProtocol {}

let myTest : FirstProtocol?

myTest = TestClass() as FirstProtocol

let secondTest: SecondProtocol?

secondTest = myTest as! SecondProtocol

所以最后一行导致 Swift 崩溃。从某种意义上说,我明白为什么。然而 secondTest 是从主程序而不是 Pod secondTest 实例化的,所以 SecondTest 对 SecondProtocol 一无所知。然而,第二个 pod 需要第二个协议的输入。

那么如何让 secondTest 转换为 SecondProtocol?

您所缺少的只是让 TestClass 符合 SecondProtocol,就像您为 FirstProtocol 所做的那样:

extension TestClass : SecondProtocol {}

您可以为在其他模块(例如 Foundation 或 UIKit 以及第三方依赖项)中定义的 类、结构和枚举指定协议一致性。