[英]How can I use type(of: someVar) as a proper Type in Swift?
如何在Swift type(of: someVar)
用作適當的Type?
假設我有一些通用協議Requestable:
protocol Decryptable: Decodable {
var cipher: Cipher
}
protocol Requestable {
associatedtype T
var schema: T
}
protocol Service {
static func invoke<R: Requestable>(_ request: R) -> Void where R.T: Decodable {
// impl. #1
}
static func invoke<R: Requestable>(_ request: R) -> Void where R.T: Decryptable {
// impl. #2
}
}
struct Request<T>: Requestable {
var schema: T
}
服務可以調用架構可解碼或可解密的請求。
但是,由於Decryptable符合Decodable,因此在其他地方,我們已經將某些Decryptable值轉換為Decodable,例如:
let myDecodable = myDecryptable as Decodable
// later... in a class that doesn’t know about myDecryptable...
let myRequest = Request(schema: myDecodable)
Service.invoke(myRequest)
現在,當在這里調用Service invoke時,它將路由到第一個實現(#1)。 即,由於請求是使用向上轉換的值“ myDecodable”創建的,因此調用將轉到實現1(好像Request.T只是某種Decodable類型,而實際上它是Decryptable類型)。
確實,如果我在XCode中設置斷點,則運行時將清楚地知道Request.T在每種情況下都是Decryptable類型,即使是在更新之后也是如此。
因此,在實現1中,我嘗試了很多方法將模式可解密的調用路由到實現2:
typealias ActualType: Decryptable = R.T
if let downcastedRequest = request as? Request<ActualType> {
invoke(downcastedRequest)
}
// FAILS to compile
let schemaType = type(of: request.schema)
if let downcastedRequest = Request<schemaType>(schema: request.schema as? schemaType) {
invoke(downcastedRequest)
}
// FAILS to compile
if let downcastedRequest = Request<type(of: request.schema)>(schema: request.schema as? type(of: request.schema)) {
invoke(downcastedRequest)
}
// FAILS to compile
請幫忙,謝謝。 (我愚蠢地嘗試使用具有關聯類型的協議嗎?為什么我不能在這里將type(of:schema)當作正確的Type來使用呢?
使用==代替:
<...>
where R.T == Decodable <...>
where R.T == Decryptable <...>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.