如何检查与 Swift 中关联类型的协议的一致性?
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 {}
编译器将显示以下错误:
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符合协议
class A: ExampleProtocol {
typealias SomeType = String
func foo(param: SomeType) {
}
}
编译器开始是这样看的:
protocol ExampleProtocol {
func foo(param: String)
}
然后然后可以比较类型
当我想检查一个类型是否符合一个简单的协议时,我可以使用:
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符合协议
class A: ExampleProtocol {
typealias SomeType = String
func foo(param: SomeType) {
}
}
编译器开始是这样看的:
protocol ExampleProtocol {
func foo(param: String)
}
然后然后可以比较类型