加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:38:57 所属栏目:百科 来源:网络整理
导读:当我想检查类型是否符合简单协议时,我可以使用: if let type = ValueType.self as? Codable.Type {} 当协议具有关联类型时,例如RawRepresentable具有RawValue,当我这样做时: if let type = ValueType.self as? RawRepresentable.Type {} 编译器将显示以下
当我想检查类型是否符合简单协议时,我可以使用:

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)
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读