Swift中Printable和DebugPrintable的区别

cfi*_*her 12 cocoa protocols swift

在寻找Swift相当于Cocoa的时候description,我在Swift中找到了以下协议:PrintableDebugPrintable.

这两个协议之间的区别是什么?我应该在何时使用每个协议?

Gen*_*isa 19

这是一个示例类

class Foo: Printable, DebugPrintable {
    var description: String {
        return "Foo"
    }
    var debugDescription: String {
        return "debug Foo"
    }
}
Run Code Online (Sandbox Code Playgroud)

这是如何使用它.

println(Foo())
debugPrintln(Foo())
Run Code Online (Sandbox Code Playgroud)

这是输出,没有惊喜:

Foo
debug Foo
Run Code Online (Sandbox Code Playgroud)

我没有在游乐场尝试这个.它适用于实际项目.

上面的答案是针对Swift 1.当时是正确的.

Swift 2的更新.

println和debugPrintln消失,协议已重命名.

class Foo: CustomStringConvertible, CustomDebugStringConvertible {
    var description: String {
        return "Foo"
    }
    var debugDescription: String {
        return "debug Foo"
    }
}

print(Foo())
debugPrint(Foo())
Run Code Online (Sandbox Code Playgroud)


Bil*_*ner 4

在 Xcode 6 Beta(版本 6.2 (6C101))中,我发现 println 和 debugPrintln 都使用描述当且仅当该类源自 NSObject。我没有看到两者都使用 debugDescription ,但在 Playground 中运行时 debugPrintln 仅输出到控制台,并且不会出现在 Playground 本身中。

import Foundation

class Tdesc: NSObject, Printable, DebugPrintable {
    override var description: String {return "A description"}
    override var debugDescription: String {return "A debugDescription"}
}

class Xdesc: Printable, DebugPrintable {
    var description: String {return "A description"}
    var debugDescription: String {return "A debugDescription"}
}

let t = Tdesc()
let x = Xdesc()

t.description

let z: String = "x\(t)"

println(t)      // Displays "A description" in the Playground and Console

debugPrintln(t) // Displays nothing in the Playground but "A description" in the Console

x.description

let y: String = "x\(x)"

println(x)      // Displays "__lldb_expr_405.Xdesc" in the Playground and Console

debugPrintln(x)
Run Code Online (Sandbox Code Playgroud)