微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

if let type = ValueType.self as? Codable.Type {}

当协议具有关联类型时,例如RawRepresentable具有RawValue,当我这样做时:

if let type = ValueType.self as? RawRepresentable.Type {}

编译器将显示以下错误

Protocol ‘RawRepresentable’ can only be used as a generic constraint because it has Self or associated type requirements

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

解决方法

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

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

protocol ExampleProtocol {
    associatedtype SomeType
    func foo(param: SomeType)
}

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

protocol ExampleProtocol {
    func foo(param: <I don't kNow it,so I'll wait until it's defined>)
}

声明符合协议的类时

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

    }
}

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

protocol ExampleProtocol {
    func foo(param: String)
}

然后它能够​​比较类型.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐