在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)
相反,我必须显式地调用description:
8> println("x = \(x.description)")
x = MyClass, foo = 42
有没有更好的方法?
发布于 2014-06-09 01:38:56
要在Swift类型上实现这一点,您必须实现CustomStringConvertible
协议,然后还实现一个名为description
的字符串属性。
例如:
class MyClass: CustomStringConvertible {
let foo = 42
var description: String {
return "<\(type(of: self)): foo = \(foo)>"
}
}
print(MyClass()) // prints: <MyClass: foo = 42>
注意:type(of: self)
获取当前实例的类型,而不是显式地写入‘MyClass’。
发布于 2015-06-24 19:41:39
只需使用CustomStringConvertible
和var description: String { return "Some string" }
即可
适用于Xcode 7.0测试版
class MyClass: CustomStringConvertible {
var string: String?
var description: String {
//return "MyClass \(string)"
return "\(self.dynamicType)"
}
}
var myClass = MyClass() // this line outputs MyClass nil
// and of course
print("\(myClass)")
// Use this newer versions of Xcode
var description: String {
//return "MyClass \(string)"
return "\(type(of: self))"
}
发布于 2016-01-11 19:05:33
与CustomStringConvertible
相关的答案是要走的路。就个人而言,为了尽可能保持类(或结构)定义的整洁,我还会将描述代码分离到一个单独的扩展中:
class foo {
// Just the basic foo class stuff.
var bar = "Humbug!"
}
extension foo: CustomStringConvertible {
var description: String {
return bar
}
}
let xmas = foo()
print(xmas) // Prints "Humbug!"
https://stackoverflow.com/questions/24108634
复制相似问题