![](/img/trans.png)
[英]Swift protocol conformance with associated type using same-type constraint
[英]How to check conformance to protocol with associated type in Swift?
当我想检查类型是否符合简单协议时,我可以使用:
if let type = ValueType.self as? Codable.Type {}
当协议具有关联类型时,例如RawRepresentable
具有RawValue
,当我这样做时:
if let type = ValueType.self as? RawRepresentable.Type {}
编译器将显示以下错误:
协议'RawRepresentable'只能用作通用约束,因为它具有Self或相关类型要求
那么如何检查协议与相关类型的一致性?
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)
}
然后它能够比较类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.