首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >-[NSObject description]的Swift等价物是什么?

-[NSObject description]的Swift等价物是什么?
EN

Stack Overflow用户
提问于 2014-06-09 01:09:42
回答 6查看 43.6K关注 0票数 173

在Objective-C中,可以将description方法添加到它们的类中以帮助调试:

代码语言:javascript
复制
@implementation MyClass
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end

然后在调试器中,您可以执行以下操作:

代码语言:javascript
复制
po fooClass
<MyClass: 0x12938004, foo = "bar">

Swift中的等价物是什么?Swift的REPL输出可能会有所帮助:

代码语言:javascript
复制
  1> class MyClass { let foo = 42 }
  2> 
  3> let x = MyClass()
x: MyClass = {
  foo = 42
}

但是为了打印到控制台,我想重写这个行为:

代码语言:javascript
复制
  4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)

有没有办法清理这个println输出?我看过Printable协议:

代码语言:javascript
复制
/// 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“看到”,但事实似乎并非如此:

代码语言:javascript
复制
  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:

代码语言:javascript
复制
 8> println("x = \(x.description)")
x = MyClass, foo = 42

有没有更好的方法?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2014-06-09 01:38:56

要在Swift类型上实现这一点,您必须实现CustomStringConvertible协议,然后还实现一个名为description的字符串属性。

例如:

代码语言:javascript
复制
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’。

票数 133
EN

Stack Overflow用户

发布于 2015-06-24 19:41:39

只需使用CustomStringConvertiblevar description: String { return "Some string" }即可

适用于Xcode 7.0测试版

代码语言:javascript
复制
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))"
}
票数 37
EN

Stack Overflow用户

发布于 2016-01-11 19:05:33

CustomStringConvertible相关的答案是要走的路。就个人而言,为了尽可能保持类(或结构)定义的整洁,我还会将描述代码分离到一个单独的扩展中:

代码语言:javascript
复制
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!"
票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24108634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档