可以使用Mirror来获取类的成员变量和属性,然后将其打印成字符串。以下是一个示例代码:

class Person {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

extension CustomStringConvertible {
    var description: String {
        let mirror = Mirror(reflecting: self)
        var description = "\(mirror.subjectType)("
        
        for child in mirror.children {
            if let propertyName = child.label {
                description += "\(propertyName): \(child.value), "
            }
        }
        
        if description.hasSuffix(", ") {
            description.removeLast(2)
        }
        
        description += ")"
        return description
    }
}

let person = Person(name: "John Doe", age: 25)
print(person)

输出结果将会是Person(name: "John Doe", age: 25)。在上述代码中,我们通过在CustomStringConvertible协议中实现description属性,使用Mirror反射获取类的成员变量和属性,并将其拼接成字符串

中文回答Swift 将class数据转成整体字符串打印

原文地址: https://www.cveoy.top/t/topic/hEBS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录