gpt4 book ai didi

swift - 在 Swift 中,如何转换为具有关联类型的协议(protocol)?

转载 作者:IT王子 更新时间:2023-10-29 05:12:33 27 4
gpt4 key购买 nike

在下面的代码中,我想测试x 是否是一个SpecialController。如果是,我想获取 currentValue 作为 SpecialValue。你怎么做到这一点?如果不使用类型转换,则使用其他一些技术。

那里的最后一行不会编译。错误是:Protocol "SpecialController"can only be used as a generic constraint because it has Self or associated type requirements.

protocol SpecialController {
associatedtype SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}
...
var x: AnyObject = ...
if let sc = x as? SpecialController { // does not compile

最佳答案

不幸的是,Swift 目前不支持将具有关联类型的协议(protocol)用作实际类型。然而这is technically possible为编译器做;它may well be implemented in a future version of the language .

在您的情况下,一个简单的解决方案是定义 SpecialController 派生的“影子协议(protocol)”,并允许您通过类型删除它的协议(protocol)要求访问 currentValue :

// This assumes SpecialValue doesn't have associated types – if it does, you can
// repeat the same logic by adding TypeErasedSpecialValue, and then using that.
protocol SpecialValue {
// ...
}

protocol TypeErasedSpecialController {
var typeErasedCurrentValue: SpecialValue? { get }
}

protocol SpecialController : TypeErasedSpecialController {
associatedtype SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}

extension SpecialController {
var typeErasedCurrentValue: SpecialValue? { return currentValue }
}

extension String : SpecialValue {}

struct S : SpecialController {
var currentValue: String?
}

var x: Any = S(currentValue: "Hello World!")
if let sc = x as? TypeErasedSpecialController {
print(sc.typeErasedCurrentValue as Any) // Optional("Hello World!")
}

关于swift - 在 Swift 中,如何转换为具有关联类型的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40387960/

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