遍历结构的静态属性 [英] Iterate over static properties of a struct

查看:91
本文介绍了遍历结构的静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来遍历结构的所有属性?我熟悉的非静态属性的方法是使用 Mirror ,但是当该结构仅包含静态属性时,它将返回一个空数组.这是我要实现的目标的一个示例:

Is there a simple way to iterate over all of the properties of a struct? The approach for non-static properties that I am familiar with is using Mirror, but this returns an empty array when the struct contains only static properties. Here's an example of what I am trying to achieve:

struct Tree {
    static let bark = "Bark"
    static let roots = "Roots"
}

let treeParts = [String]()
// insert code here to make treeParts = ["Bark", "Roots"]

推荐答案

由于我也对如何执行此操作感兴趣,因此在下面创建了示例.为什么不只创建具有非静态属性的结构,再加上使该结构成为单例的静态实例变量.以下代码示例详细说明了使用REST API的命名语义将Person对象的值映射到JSON字典的示例用例. PersonJSONKeys的属性名称必须与Person的属性名称匹配.

Since I also have an interest of how to do this I made the example below. Why not just create the struct with non static properties plus a static instance variable which makes the struct a singleton. The following code sample details an example use case for mapping values of a Person object to a JSON dictionary using the REST API's naming semantics. The property names of PersonJSONKeys have to match the property names of Person.

allProperties()函数的代码来自如何循环超过Swift中的struct属性?.您可以轻松修改此函数,使其仅返回structs属性的值.

The code for the allProperties() function comes from How to loop over struct properties in Swift?. You can modify this function easily to only return the values of a structs properties.

struct PersonJSONKeys: PropertyLoopable {
    static let instance: PersonJSONKeys = PersonJSONKeys()
    private init() {}

    let name = "name"
    let firstName = "first_name"
    let age = "age"
}

struct Person: PropertyLoopable {
    let name = "Doe"
    let firstName = "John"
    let age = "18"
}

let person = Person()
let personProperties = person.allProperties()
var personJSON: [String:Any] = [:]

for jsonProperty in PersonJSONKeys.instance.allProperties() {
    let propertyName = jsonProperty.key
    let jsonKey = jsonProperty.value as! String
    personJSON[jsonKey] = personProperties[propertyName]
}

由于Struct现在是单例,因此其所有属性将仅初始化一次,并且线程安全性由其静态实例变量提供.

Since the Struct is now a singleton all of its properties will be initialised only once and the thread safety is given by its static instance variable.

这篇关于遍历结构的静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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