In Objective-C, è possibile aggiungere un description
metodo alla loro classe per facilitare il debug:
@implementation MyClass
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end
Quindi nel debugger puoi fare:
po fooClass
<MyClass: 0x12938004, foo = "bar">
Qual è l'equivalente in Swift? L'output REPL di Swift può essere utile:
1> class MyClass { let foo = 42 }
2>
3> let x = MyClass()
x: MyClass = {
foo = 42
}
Ma vorrei ignorare questo comportamento per la stampa sulla console:
4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)
C'è un modo per ripulire questo println
output? Ho visto il Printable
protocollo:
/// 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 }
}
Ho pensato che questo sarebbe automaticamente "visto" da println
ma non sembra essere il caso:
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)
E invece devo chiamare esplicitamente la descrizione:
8> println("x = \(x.description)")
x = MyClass, foo = 42
C'è un modo migliore?