In Objective-C kann man eine description
Methode zu ihrer Klasse hinzufügen:Was ist das Swift-Äquivalent von - [NSObject-Beschreibung]? bei der Fehlersuche zu unterstützen
@implementation MyClass
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end
dann in dem Debugger können Sie tun:
po fooClass
<MyClass: 0x12938004, foo = "bar">
Was ist das Äquivalent in Swift ? Swifts REPL Ausgang kann hilfreich sein:
1> class MyClass { let foo = 42 }
2>
3> let x = MyClass()
x: MyClass = {
foo = 42
}
Aber ich möchte dieses Verhalten außer Kraft zu setzen für den Druck auf die Konsole:
4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)
Gibt es eine Möglichkeit, diese println
Ausgabe zu bereinigen? Ich habe das Printable
Protokoll gesehen:
/// 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 }
}
ich dies automatisch durch println
dachte würde „gesehen“, aber es scheint nicht der Fall zu sein:
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)
Und stattdessen muss ich ausdrücklich nennen Beschreibung:
8> println("x = \(x.description)")
x = MyClass, foo = 42
Gibt es einen besseren Weg?
Toller Fund! Ich werde eine Radar-Println-Ausgabe von "swift -i sample.swift" und "swift sample.swift && sample" eingeben. – Jason
Danke für die Info dazu. Ich habe Printable auf einem Spielplatz ausprobiert und es funktioniert tatsächlich gerade nicht. Gut hört es sich in einer App an. –
Printable funktioniert auf dem Spielplatz, aber wenn die Klasse von NSObject abstammt – dar512