Di Objective-C, seseorang dapat menambahkan description
metode ke kelas mereka untuk membantu dalam debugging:
@implementation MyClass
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end
Kemudian di debugger, Anda bisa melakukan:
po fooClass
<MyClass: 0x12938004, foo = "bar">
Apa yang setara di Swift? Output REPL Swift dapat membantu:
1> class MyClass { let foo = 42 }
2>
3> let x = MyClass()
x: MyClass = {
foo = 42
}
Tapi saya ingin mengganti perilaku ini untuk mencetak ke konsol:
4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)
Apakah ada cara untuk membersihkan println
output ini ? Saya telah melihat Printable
protokolnya:
/// 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 }
}
Saya pikir ini akan secara otomatis "dilihat" oleh println
tetapi tampaknya tidak terjadi:
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)
Dan sebaliknya saya harus secara eksplisit memanggil deskripsi:
8> println("x = \(x.description)")
x = MyClass, foo = 42
Apakah ada cara yang lebih baik?