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

Jas*_*son 151 swift

在Objective-C中,可以description向其类添加一个方法以帮助调试:

@implementation MyClass
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end
Run Code Online (Sandbox Code Playgroud)

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

po fooClass
<MyClass: 0x12938004, foo = "bar">
Run Code Online (Sandbox Code Playgroud)

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

  1> class MyClass { let foo = 42 }
  2> 
  3> let x = MyClass()
x: MyClass = {
  foo = 42
}
Run Code Online (Sandbox Code Playgroud)

但我想重写此行为以打印到控制台:

  4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)
Run Code Online (Sandbox Code Playgroud)

有没有办法清理这个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 }
}
Run Code Online (Sandbox Code Playgroud)

我认为这会自动被"看到",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)
Run Code Online (Sandbox Code Playgroud)

相反,我必须明确地称之为描述:

 8> println("x = \(x.description)")
x = MyClass, foo = 42
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

dre*_*wag 110

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

例如:

class MyClass: CustomStringConvertible {
    let foo = 42

    var description: String {
        return "<\(type(of: self)): foo = \(foo)>"
    }
}

print(MyClass()) // prints: <MyClass: foo = 42>
Run Code Online (Sandbox Code Playgroud)

注意:type(of: self)获取当前实例的类型而不是显式写入"MyClass".

  • 在Swift 2.0中,它已更改为CustomStringConvertible和CustomDebugStringConvertible (5认同)
  • 很棒的发现!我要提交雷达 - println输出"swift -i sample.swift"和"swift sample.swift && sample"不同. (3认同)

Kin*_*ard 53

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

            ...
}
Run Code Online (Sandbox Code Playgroud)

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

          ...
}
Run Code Online (Sandbox Code Playgroud)

打印出来的:

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

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

---- PageContentViewController
pageIndex equals 0 ----
Run Code Online (Sandbox Code Playgroud)

注意:如果您的自定义类不从UIKitFoundation库中包含的任何类继承,则使其继承NSObject类或使其符合CustomStringConvertibleCustomDebugStringConvertible协议.


Pet*_*erg 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))"
}
Run Code Online (Sandbox Code Playgroud)


Vin*_*van 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!"
Run Code Online (Sandbox Code Playgroud)


Pet*_*erg 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
Run Code Online (Sandbox Code Playgroud)


Sir*_*lot 8

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)


neo*_*eye 5

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
Run Code Online (Sandbox Code Playgroud)