What is the Swift equivalent of -[NSObject description]?

前端 未结 7 1133
不思量自难忘°
不思量自难忘° 2020-12-23 02:25

In Objective-C, one can add a description method to their class to aid in debugging:

@implementation MyClass
- (NSString *)description
{
    ret         


        
7条回答
  •  一整个雨季
    2020-12-23 03:08

    As described here, you can also use Swift's reflection capabilities to make your classes generate their own description by using this extension:

    extension CustomStringConvertible {
        var description : String {
            var description: String = "\(type(of: self)){ "
            let selfMirror = Mirror(reflecting: self)
            for child in selfMirror.children {
                if let propertyName = child.label {
                    description += "\(propertyName): \(child.value), "
                }
            }
            description = String(description.dropLast(2))
            description += " }"
            return description
        }
    }
    

提交回复
热议问题