gpt4 book ai didi

class - 如何在swift中列出一个类的所有变量

转载 作者:IT王子 更新时间:2023-10-29 05:29:18 27 4
gpt4 key购买 nike

有没有办法在 Swift 中列出一个类的所有变量?

例如:

class foo {
var a:Int? = 1
var b:String? = "John"
}

我想这样列出:[a:1, b:"John"]

最佳答案

如何在 Swift 3.0 中递归执行此操作:

import Foundation

class FirstClass {
var name = ""
var last_name = ""
var age = 0
var other = "abc"

func listPropertiesWithValues(reflect: Mirror? = nil) {
let mirror = reflect ?? Mirror(reflecting: self)
if mirror.superclassMirror != nil {
self.listPropertiesWithValues(reflect: mirror.superclassMirror)
}

for (index, attr) in mirror.children.enumerated() {
if let property_name = attr.label {
//You can represent the results however you want here!!!
print("\(mirror.description) \(index): \(property_name) = \(attr.value)")
}
}
}

}


class SecondClass: FirstClass {
var yetAnother = "YetAnother"
}

var second = SecondClass()
second.name = "Name"
second.last_name = "Last Name"
second.age = 20

second.listPropertiesWithValues()

结果:

Mirror for FirstClass 0: name = Name
Mirror for FirstClass 1: last_name = Last Name
Mirror for FirstClass 2: age = 20
Mirror for FirstClass 3: other = abc
Mirror for SecondClass 0: yetAnother = YetAnother

关于class - 如何在swift中列出一个类的所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27928279/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com