You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断对象是否为基于ProtocolA的OtherStruct泛型实例?

Swift 判断泛型结构体实例匹配存在类型泛型的解决办法

你写的if obj is OtherStruct<any ProtocolA>无法运行,核心原因是:OtherStruct<some ProtocolA>是泛型约束(要求类型参数必须是ProtocolA的具体实现),而OtherStruct<any ProtocolA>是基于存在类型的泛型实例类型,两者不属于同一类型体系——你的obj实际类型是OtherStruct<MyStruct>,是具体类型的泛型实例,和存在类型的泛型实例不匹配。

下面提供两种可行的解决思路:

方案1:类型擦除(快速判断是否为OtherStruct实例)

如果你的需求只是确认对象是OtherStruct的实例(由于泛型约束,所有OtherStruct实例的类型参数必然遵循ProtocolA),可以通过定义空协议做类型擦除:

protocol ProtocolA {}

struct MyStruct: ProtocolA {}

// 新增类型擦除协议,所有OtherStruct实例自动遵循
protocol AnyOtherStruct {}
struct OtherStruct<T: ProtocolA>: AnyOtherStruct {}

let obj = OtherStruct<MyStruct>()

// 正常判断
if obj is AnyOtherStruct {
    // 执行你的逻辑
}

方案2:泛型辅助函数(精确校验类型参数约束)

如果需要更精确的校验(比如后续可能调整泛型约束,需要确保类型参数确实遵循ProtocolA),可以用泛型辅助函数实现:

protocol ProtocolA {}

struct MyStruct: ProtocolA {}
struct OtherStruct<T: ProtocolA> {}

let obj = OtherStruct<MyStruct>()

// 泛型判断函数
func isOtherStructConformingToProtocolA(_ value: Any) -> Bool {
    func matches<T: ProtocolA>(_: OtherStruct<T>.Type) -> Bool { true }
    return value is OtherStruct<some ProtocolA>
}

// 使用示例
if isOtherStructConformingToProtocolA(obj) {
    // 执行你的逻辑
}

补充说明

any ProtocolA是Swift的存在类型,用于擦除具体类型信息;而some ProtocolA是泛型约束,要求类型参数是ProtocolA的具体实现。OtherStruct<any ProtocolA>代表的是“类型参数为存在类型的泛型实例”,和你创建的OtherStruct<MyStruct>(具体类型的泛型实例)在类型系统中是完全不同的实体,因此直接用is运算符无法匹配。

内容的提问来源于stack exchange,提问作者Dhiogo Brustolin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:50:40