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

前端 未结 7 1130
不思量自难忘°
不思量自难忘° 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:21

    The answers relating to CustomStringConvertible are the way to go. Personally, to keep the class (or struct) definition as clean as possible, I would also separate out the description code into a separate extension:

    class foo {
        // Just the basic foo class stuff.
        var bar = "Humbug!"
    }
    
    extension foo: CustomStringConvertible {
        var description: String {
            return bar
        }
    }
    
    let xmas = foo()
    print(xmas)  // Prints "Humbug!"
    
    0 讨论(0)
提交回复
热议问题