最佳答案
在 Objective-C 中,可以在类中添加一个 description
方法来帮助调试:
@implementation MyClass
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end
然后在调试器中,您可以执行以下操作:
po fooClass
<MyClass: 0x12938004, foo = "bar">
什么是 Swift 的等价物? Swift 的 REPL 输出可能有所帮助:
1> class MyClass { let foo = 42 }
2>
3> let x = MyClass()
x: MyClass = {
foo = 42
}
但是我想覆盖打印到控制台的这个行为:
4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)
有没有办法清理这个 println
输出? 我看过 Printable
协议:
/// This protocol should be adopted by types that wish to customize their
/// textual representation. This textual representation is used when objects
/// are written to an `OutputStream`.
protocol Printable {
var description: String { get }
}
我认为 println
会自动“看到”这一点,但事实似乎并非如此:
1> class MyClass: Printable {
2. let foo = 42
3. var description: String { get { return "MyClass, foo = \(foo)" } }
4. }
5>
6> let x = MyClass()
x: MyClass = {
foo = 42
}
7> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)
相反,我必须明确地称之为描述:
8> println("x = \(x.description)")
x = MyClass, foo = 42
还有更好的办法吗?