如何在Swift中循环结构属性? [英] How to loop over struct properties in Swift?

查看:102
本文介绍了如何在Swift中循环结构属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Swift中迭代结构的属性?

Is it possible to iterate over properties of a struct in Swift?

我需要在视图控制器中注册单元重用标识符,该控制器使用许多不同的单元格类型(单元格组织在不同的nib文件中)。所以我的想法是将所有重用标识符和相应的nib文件作为静态元组属性(reuseID,nibName)放在结构中。但是,如何迭代所有这些以使用tableView注册单元格?

I need to register cells-reuse identifiers in a view controller that makes use of many different cell types (cells are organized in different nib files). So my idea was to put all reuse identifiers and the corresponding nib-files as static tuple-properties (reuseID, nibName) in a struct. But how can I iterate over all of them to register the cells with the tableView?

我已经尝试了一些东西(见下面的答案)。但有没有更简单的方法来做到这一点,例如没有把每个属性都放在一个数组中?

I already tried something (see my answer below). But is there a more easy way to do this, e.g. without putting every property inside an array?

推荐答案

虽然老问题,随着Swift的发展,这个问题有了新的答案。我认为你的方法对于描述的情况更好,但是原始的问题是如何迭代结构属性,所以这是我的答案(适用于类和结构

Although old question, with Swift evolving this question has new answer. I think that you approach is way better for the described situation, however original question was how to iterate over struct properties, so here is my answer(works both for classes and structs)

您可以使用 镜子结构参考 。关键是在将反映调用到某个对象之后,你会得到它的镜像,这是非常谨慎但仍然有用的反射。

You can use Mirror Structure Reference. The point is that after calling reflect to some object you get it's "mirror" which is pretty sparingly however still useful reflection.

因此我们可以轻松声明以下协议,其中 key 是属性的名称,是实际的值:

So we could easily declare following protocol, where key is the name of the property and value is the actual value:

protocol PropertyLoopable
{
    func allProperties() throws -> [String: Any]
}

当然我们应该使用新的协议扩展来提供此协议的默认实现:

Of course we should make use of new protocol extensions to provide default implementation for this protocol:

extension PropertyLoopable
{
    func allProperties() throws -> [String: Any] {

        var result: [String: Any] = [:]

        let mirror = Mirror(reflecting: self)

        guard let style = mirror.displayStyle where style == .Struct || style == .Class else {
            //throw some error
            throw NSError(domain: "hris.to", code: 777, userInfo: nil)
        }

        for (labelMaybe, valueMaybe) in mirror.children {
            guard let label = labelMaybe else {
                continue
            }

            result[label] = valueMaybe
        }

        return result
    }
}



<那么现在我们可以用这个循环遍历任何 struct 的属性方法。我们只需将该类标记为 PropertyLoopable

So now we can loop over the properties of any class or struct with this method. We just have to mark the class as PropertyLoopable.

为了保持静态(如示例所示),我还会添加一个单身:

In order to keep things static(as in the example) I will add also a singleton:

struct ReuseID: PropertyLoopable {
    static let instance: ReuseID = ReuseID()
}

无论是否使用单身,我们最终都可以循环遍历以下属性:

Whether singleton used or not, we could finally loop over the properties like follows:

do {
    print(try ReuseID.instance.allProperties())
} catch _ {

}

这就是循环结构属性。享受快捷;)

And that's it with looping struct properties. Enjoy swift ;)

这篇关于如何在Swift中循环结构属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆