[英]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.