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

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

    Just use CustomStringConvertible and var description: String { return "Some string" }

    works in Xcode 7.0 beta

    class MyClass: CustomStringConvertible {
      var string: String?
    
    
      var description: String {
         //return "MyClass \(string)"
         return "\(self.dynamicType)"
      }
    }
    
    var myClass = MyClass()  // this line outputs MyClass nil
    
    // and of course 
    print("\(myClass)")
    
    // Use this newer versions of Xcode
    var description: String {
        //return "MyClass \(string)"
        return "\(type(of: self))"
    }
    

提交回复
热议问题