如何在Swift中检查与协议类型的协议的一致性?

dua*_*uan 4 associated-types swift swift-protocols

当我想检查类型是否符合简单协议时,我可以使用:

if let type = ValueType.self as? Codable.Type {}
Run Code Online (Sandbox Code Playgroud)

当协议具有相关联的类型,例如RawRepresentable具有RawValue,当我做:

if let type = ValueType.self as? RawRepresentable.Type {}
Run Code Online (Sandbox Code Playgroud)

编译器将显示以下错误:

协议'RawRepresentable'只能用作通用约束,因为它具有Self或相关类型要求


那么如何检查协议与相关类型的一致性?

few*_*ode 5

TL; DR
编译器没有足够的信息来比较类型,直到设置了关联类型.


当您引用简单协议时,编译器从一开始就知道它的类型.但是,当您引用具有关联类型的协议时,编译器在您声明它之前不会知道它的类型.

protocol ExampleProtocol {
    associatedtype SomeType
    func foo(param: SomeType)
}
Run Code Online (Sandbox Code Playgroud)

此时编译器看起来像这样:

protocol ExampleProtocol {
    func foo(param: <I don't know it, so I'll wait until it's defined>)
}
Run Code Online (Sandbox Code Playgroud)

声明符合协议的类时

class A: ExampleProtocol {
    typealias SomeType = String
    func foo(param: SomeType) {

    }
}
Run Code Online (Sandbox Code Playgroud)

编译器开始看到它像这样:

protocol ExampleProtocol {
    func foo(param: String)
}
Run Code Online (Sandbox Code Playgroud)

而且那么它能够比较类型.