如何在 Swift 中传递通用结构并获取其属性列表

问题描述 投票:0回答:2

我的项目中有多个结构,我需要结构中的属性列表。所以基本上我需要一个实用函数,我应该能够将结构传递给它,并且该函数应该返回结构中属性的字符串数组。

struct TestModel: Codable {
    let id: Int
    let secondsSinceEpoch: Int

    init(id: Int, secondsSinceEpoch: Int) {
        self.id = id
        self.secondsSinceEpoch = secondsSinceEpoch
    }

    func propertyNames()  -> [String] {
        let mirror = Mirror(reflecting: self)
        return mirror.children.compactMap{ $0.label }
    }
}

在这里,我使用函数

propertyNames()
TestModel
获取属性名称。

let propertyList = TestModel(id: 1, secondsSinceEpoch: 2).propertyNames()

同样,我需要一个像这样的通用函数。

func propertyNames<T>(structure: T)  -> [String] {
    let mirror = Mirror(reflecting: T.self)
    return mirror.children.compactMap{ $0.label }
}

我应该能够传递任何结构来获取属性列表。

let propertyList = propertyNames(structure: TestModel.self)

但这会返回一个空数组。

swift generics struct
2个回答
0
投票

我认为你的方法有错字。正确的版本是:

func propertyNames<T>(structure: T)  -> [String] {
    let mirror = Mirror(reflecting: structure)
    return mirror.children.compactMap{ $0.label }
}

之前,它镜像的是 type 而不是该类型的实例。它还与

TestModel
内部的实现相匹配。


0
投票

我不太确定你在问什么,但这可能是解决方案:

您实际上可以将类或结构(而不仅仅是对象本身)传递给

Mirror

        let smirror = Mirror(reflecting: SomeStruct.self)
        for (name, value) in smirror.children {
            print("\(name) .. \(value)")
        }

这就是您所需要的吗?

© www.soinside.com 2019 - 2024. All rights reserved.