列出所有类属性Swift 3



我正在尝试从类继承的对象中打印所有值,这是我的示例:

我创建类:

 class Pokemon {
 var name: String?
 var type: String?
 var level: Int?
 var exp = 0.0
}

创建对象并分配一些值:

var pikachu = Pokemon()
pikachu.name = "Pika Pika"
pikachu.level = 1
pikachu.type = "electricity"
pikachu.exp = 0

现在,我想循环浏览所有Pikachu对象属性并打印值。我正在考虑每个循环,但我不确定如何实施。

我知道我可以做这样的事情:

func printStats(pokemon: Pokemon) {
if pokemon.name != nil {
    print(" name: (pokemon.name!)n level:(pokemon.level!)n type:(pokemon.type!)n exp: (pokemon.exp!)")
 }
}
printStats(pokemon: pikachu)

输出:

name: Pika Pika
level:1
type:electricity
exp: 0.0

,但我只想循环遍历所有值,而不是明确编写函数中的每个属性。

我找到了它的方法:

let pokeMirror = Mirror(reflecting: pikachu)
let properties = pokeMirror.children
for property in properties {
  print("(property.label!) = (property.value)")
}

输出:

name = Optional("Pika Pika")
type = Optional("electricity")
level = Optional(1)
exp = Optional(0.0)

,如果要删除"可选",只需初始化属性。

在Swift 5中您可以在类中创建一个新的func

func debugLog() {
    print(Mirror(reflecting: self).children.compactMap { "($0.label ?? "Unknown Label"): ($0.value)" }.joined(separator: "n"))
}

,然后用MyObject().debugLog()

调用它

看起来像是Swift支持反射的重复?

另外,您可以使用字典来存储Any?类型的属性。

,例如

class Pokemon {
    var attributes = [String:Any?]()
}
var pikachu = Pokemon()
pikachu.attributes["name"] = "Pika Pika"
pikachu.attributes["level"] = 1
pikachu.attributes["type"] = "electricity"
pikachu.attributes["exp"] = 0
func printStats(pokemon: Pokemon) {
    pokemon.attributes.forEach { key, value in
        if let value = value {
            print("(key): (value)")
        }
    }
}
    1. 使用Mirror API获取实例属性
    1. 如果您正在开发iOS应用程序,则使用nsobject,则可能需要覆盖描述。然后可以使用print打印实例。

镜子描述了构成特定实例的部分,例如实例存储的属性,集合或元组元素或其主动枚举情况。

class YourClass: NSObject {
  public override var description: String {
        var des: String = "(type(of: self)) :"
        for child in Mirror(reflecting: self).children {
            if let propName = child.label {
                des += "(propName): (child.value) n"
            }
        }
     
        return des
    }
}
let instance = YourClass()
print(instance)

在Swift

中查看更多反射中的更多信息

最新更新