加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

什么是Swift等价的 – [NSObject description]?

发布时间:2020-12-14 06:16:55 所属栏目:百科 来源:网络整理
导读:在Objective-C中,可以向它们的类中添加一个描述方法以帮助调试: @implementation MyClass- (NSString *)description{ return [NSString stringWithFormat:@"%@: %p,foo = %@",[self class],foo _foo];}@end 然后在调试器中,您可以: po fooClassMyClass:
在Objective-C中,可以向它们的类中添加一个描述方法以帮助调试:
@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输出?我看过可打印协议:

/// 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

有没有更好的办法?

通过一些实验,我发现Printable和DebugPrintable协议在编译实际应用程序时工作,而不是在REPL或Playground中工作。

Side注意:你写的代码是正确的,但在这种情况下,你可能正在寻找DebugPrintable

Swift已经将这些协议重命名为CustomStringConvertible和CustomDebugStringConvertible – 虽然编译器目前有帮助地告诉你它做了:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读