更改 print(Object) 在 Swift 2.0 中显示的内容

Change what print(Object) displays in Swift 2.0

我试图让我的 class Digit 在 Swift 2.0 中每当对该对象调用 print 时显示 num 变量。我认为这可以通过描述变量来完成,但没有成功。

class Digit {

  var num: Int
  var x: Int
  var y: Int
  var box: Int
  var hintList: [Int] = []
  var guess: Bool = false

  var description: String {
    let string = String(num)
    return string
  }
}

仅添加 description 变量是不够的。您还需要声明您的 class 符合 CustomStringConvertible(在早期的 Swift 版本中以前称为 Printable)。

如果您命令单击 print 函数,您会发现以下描述。

Writes the textual representation of value, and an optional newline, into the standard output.

The textual representation is obtained from the value using its protocol conformances, in the following order of preference: Streamable, CustomStringConvertible, CustomDebugStringConvertible. If none of these conformances are found, a default text representation is constructed in an implementation-defined way, based on the type kind and structure.

这里重要的部分是传递给 print 的对象不会检查它们是否具有 description 方法,而是检查是否符合到像 CustomStringConvertible 这样提供要打印的数据的协议。

也就是说,在这种情况下您需要做的就是指定您的 class 符合 CustomStringConvertible,因为您已经添加了一个 description 变量。如果您还没有添加它,编译器会报错,因为该协议要求实现 description 变量。

class Digit: CustomStringConvertible {
    var num: Int
    var x: Int
    var y: Int
    var box: Int
    var hintList: [Int] = []
    var guess: Bool = false

    var description: String {
        let string = String(num)
        return string
    }
}