美文网首页
Swift 获取实例的属性列表

Swift 获取实例的属性列表

作者: zackzheng | 来源:发表于2024-05-10 17:24 被阅读0次
struct Person: Codable {
    var name: String
    var age: Int
    var email: String?
}

func getProperties(of codable: Codable) -> [String] {
    let mirror = Mirror(reflecting: codable)
    return mirror.children.compactMap { $0.label }
}
 
let person = Person(name: "John Doe", age: 30, email: "john@example.com")
let propertiesList = getProperties(of: person)
print(propertiesList)

相关文章

网友评论

      本文标题:Swift 获取实例的属性列表

      本文链接:https://www.haomeiwen.com/subject/kjsefjtx.html