Swift的-[NSObject description]等效项是什么?


163

在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

有没有更好的办法?

Answers:


124

要在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”。


3
很棒的发现!我要提交一个雷达-“ swift -i sample.swift”和“ swift sample.swift && sample”的println输出有所不同。
杰森

感谢您提供的信息。我曾在操场上尝试过Printable,但现在确实无法正常工作。很好,听说它可以在应用程序中运行。
Tod Cunningham 2014年

Printable确实可以在操场上工作,但
前提

5
在Swift 2.0中,它已更改为CustomStringConvertible和CustomDebugStringConvertible
Mike Vosseller

另外,在Xcode 7.2的Playground中使用CustomStringConvertible和CustomDebugStringConvertible也没有问题
Nicholas Credli

54

在Swift 中使用CustomStringConvertibleCustomDebugStringConvertible协议的示例:

PageContentViewController.swift

import UIKit

class PageContentViewController: UIViewController {

    var pageIndex : Int = 0

    override var description : String { 
        return "**** PageContentViewController\npageIndex equals \(pageIndex) ****\n" 
    }

    override var debugDescription : String { 
        return "---- PageContentViewController\npageIndex equals \(pageIndex) ----\n" 
    }

            ...
}

ViewController.swift

import UIKit

class ViewController: UIViewController
{

    /*
        Called after the controller's view is loaded into memory.
    */
    override func viewDidLoad() {
        super.viewDidLoad()

        let myPageContentViewController = self.storyboard!.instantiateViewControllerWithIdentifier("A") as! PageContentViewController
        print(myPageContentViewController)       
        print(myPageContentViewController.description)
        print(myPageContentViewController.debugDescription)
    }

          ...
}

哪些打印出来:

**** PageContentViewController
pageIndex equals 0 ****

**** PageContentViewController
pageIndex equals 0 ****

---- PageContentViewController
pageIndex equals 0 ----

注意:如果您有一个不继承自UIKitFoundation库中包含的任何类的自定义类,请使其成为NSObject类的继承者或使其符合CustomStringConvertibleCustomDebugStringConvertible协议。


该函数必须声明为公共函数
Karsten

35

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

在Xcode 7.0 beta中工作

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))"
}

20

有关的答案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!"

8
class SomeBaseClass: CustomStringConvertible {

    //private var string: String = "SomeBaseClass"

    var description: String {
        return "\(self.dynamicType)"
    }

    // Use this in newer versions of Xcode
    var description: String {
        return "\(type(of: self))"
    }

}

class SomeSubClass: SomeBaseClass {
    // If needed one can override description here

}


var mySomeBaseClass = SomeBaseClass()
// Outputs SomeBaseClass
var mySomeSubClass = SomeSubClass()
// Outputs SomeSubClass
var myOtherBaseClass = SomeSubClass()
// Outputs SomeSubClass

6

如上所述在这里,你还可以使用雨燕的反射能力,使你的类生成自己的描述,通过使用这个扩展:

extension CustomStringConvertible {
    var description : String {
        var description: String = "\(type(of: self)){ "
        let selfMirror = Mirror(reflecting: self)
        for child in selfMirror.children {
            if let propertyName = child.label {
                description += "\(propertyName): \(child.value), "
            }
        }
        description = String(description.dropLast(2))
        description += " }"
        return description
    }
}

4
struct WorldPeace: CustomStringConvertible {
    let yearStart: Int
    let yearStop: Int

    var description: String {
        return "\(yearStart)-\(yearStop)"
    }
}

let wp = WorldPeace(yearStart: 2020, yearStop: 2040)
print("world peace: \(wp)")

// outputs:
// world peace: 2020-2040
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.