在 Objective-C 中,可以向他们的类添加一个description方法来帮助调试:
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协议:
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
有没有更好的办法?
要在 Swift 类型上实现这一点,您必须实现CustomStringConvertible协议,然后还要实现一个名为description.
CustomStringConvertible
例如:
class MyClass: CustomStringConvertible { let foo = 42 var description: String { return "<\(type(of: self)): foo = \(foo)>" } } print(MyClass()) // prints: <MyClass: foo = 42>
注意:type(of: self)获取当前实例的类型,而不是显式写“楳yClass”。
type(of: self)