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

Swift如何使用Mirror获取泛型类T的所有成员属性?

获取泛型类T的所有成员(基于Mirror实现)

没问题,我来帮你把现有代码适配到泛型场景!你当前的代码已经能处理具体类的实例,其实只要把逻辑封装成泛型函数,就能轻松支持任意泛型类的成员遍历——因为Mirror的反射逻辑是基于实例的,不管这个实例是不是泛型类的对象,都能正常解析它的结构。

泛用版实现代码

先给你一个通用的泛型函数,传入任意类型的实例就能打印它的所有属性:

func printAllProperties<T>(of instance: T) {
    let mirroredObject = Mirror(reflecting: instance)
    for (index, attr) in mirroredObject.children.enumerated() {
        // 确保属性标签不为空(有些系统生成的成员可能没有标签)
        guard let propertyName = attr.label else {
            continue
        }
        print("Attr \(index): \(propertyName) = \(attr.value)")
    }
}

用泛型类测试一下

我们定义一个泛型类,然后用上面的函数来验证效果:

// 示例泛型类
class GenericModel<T> {
    var identifier: Int = 0
    var content: T?
    private var internalTag: String = "hidden_tag"
    
    init(identifier: Int, content: T?) {
        self.identifier = identifier
        self.content = content
    }
}

// 创建不同类型的泛型实例
let stringModel = GenericModel<String>(identifier: 1, content: "泛型测试文本")
let intModel = GenericModel<Int>(identifier: 2, content: 999)

// 调用函数打印属性
print("=== String类型泛型实例属性 ===")
printAllProperties(of: stringModel)
print("\n=== Int类型泛型实例属性 ===")
printAllProperties(of: intModel)

关键说明

  • Mirror会自动遍历实例的所有可见成员:包括公开属性,同一模块内的私有属性也能被获取到;跨模块的私有成员则无法访问。
  • 如果你的需求是不依赖实例,直接获取泛型类的静态成员,那Mirror就不太适用了——这种情况需要借助Objective-C运行时API(前提是类继承自NSObject且静态成员暴露给ObjC),不过绝大多数场景下,基于实例的反射已经足够满足需求。

内容的提问来源于stack exchange,提问作者Benjamin RD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:14:27