什么是SWIFT相当于-[NSObject的描述]?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (26)

在目标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)

相反,我必须明确地调用描述:

 8> println("x = \(x.description)")
x = MyClass, foo = 42

有更好的办法吗?

提问于
用户回答回答于

通过一些实验我发现PrintableDebugPrintable协议在编译实际的应用程序时起作用。

在本例中,您可能是在寻找DebugPrintable。

SWIFT已将这些协议重命名为CustomStringConvertibleCustomDebugStringConvertible。

用户回答回答于

使用示例CustomStringConvertibleCustomDebugStringConvertibleSWIFT协议:

PageContentViewController.斯威夫特

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

            ...
}

视图控制员

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

然后使其继承NSObject类或使其符合CustomStringConvertibleCustomDebugStringConvertible协议。

扫码关注云+社区