[英]How can I use type(of: someVar) as a proper Type in Swift?
How can I use type(of: someVar)
as a proper Type in Swift? 如何在Swift type(of: someVar)
用作适当的Type?
Suppose I have some generic protocol Requestable: 假设我有一些通用协议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
}
Service can invoke a Request whose Schema is Decodable or Decryptable. 服务可以调用架构可解码或可解密的请求。
However, since Decryptable conforms to Decodable, elsewhere we have some Decryptable value that has been upcast to Decodable like: 但是,由于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)
Now, when Service invoke gets called here, it will route to the first implementation (#1). 现在,当在这里调用Service invoke时,它将路由到第一个实现(#1)。 Ie, since the request has been created with the upcasted value “myDecodable”, invoke will go to implementation #1 (as if Request.T is only some Decodable type, when in fact it's Decryptable, under the hood). 即,由于请求是使用向上转换的值“ myDecodable”创建的,因此调用将转到实现1(好像Request.T只是某种Decodable类型,而实际上它是Decryptable类型)。
Indeed, if I set breakpoints in XCode, the runtime clearly knows that Request.T is a Decryptable type in every situation, even after is was upcast. 确实,如果我在XCode中设置断点,则运行时将清楚地知道Request.T在每种情况下都是Decryptable类型,即使是在更新之后也是如此。
So inside implementation 1, I tried many things to route a call where the schema is Decryptable to implementation 2: 因此,在实现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
Please help, thanks. 请帮忙,谢谢。 (Was I stupid to try to use protocols with associated types? Why can't I use type(of: schema) as if it were a proper Type here..? (我愚蠢地尝试使用具有关联类型的协议吗?为什么我不能在这里将type(of:schema)当作正确的Type来使用呢?
Use == instead of : 使用==代替:
<...>
where R.T == Decodable <...>
where R.T == Decryptable <...>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.