gpt4 book ai didi

swift - 我如何使用类型(: someVar) as a proper Type in Swift?

转载 作者:行者123 更新时间:2023-11-30 12:03:46 25 4
gpt4 key购买 nike

如何在 Swift 中使用 type(of: someVar) 作为正确的类型?

假设我有一些可请求的通用协议(protocol):

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)

现在,当服务调用在这里被调用时,它将路由到第一个实现 (#1)。即,由于请求是使用向上转换的值“myDecodable”创建的,因此调用将转到实现 #1(就好像 Request.T 只是某种 Decodable 类型,而实际上它是可解密的,在幕后)。

事实上,如果我在 XCode 中设置断点,运行时就会清楚地知道 Request.T 在每种情况下都是可解密类型,即使在向上转换之后也是如此。

因此,在实现 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

请帮忙,谢谢。 (我尝试使用具有关联类型的协议(protocol)是不是很愚蠢?为什么我不能使用 type(of: schema) 就好像它是这里的正确类型一样......?

最佳答案

使用 == 代替 :

<...>
where R.T == Decodable <...>
where R.T == Decryptable <...>

关于swift - 我如何使用类型(: someVar) as a proper Type in Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46897839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com