Difference between Printable and DebugPrintable in Swift

后端 未结 3 527
失恋的感觉
失恋的感觉 2021-01-11 12:33

Looking for a Swift equivalent of Cocoa\'s description, I found the following protocols in Swift: Printable and DebugPrintable.

<
3条回答
  •  -上瘾入骨i
    2021-01-11 13:23

    Here is an example class

    class Foo: Printable, DebugPrintable {
        var description: String {
            return "Foo"
        }
        var debugDescription: String {
            return "debug Foo"
        }
    }
    

    This is how to use it.

    println(Foo())
    debugPrintln(Foo())
    

    Here is the output with no surprises:

    Foo
    debug Foo
    

    I didn't try this in a Playground. It works in an actual project.

    The answer above was for Swift 1. It was correct at the time.

    Update for Swift 2.

    println and debugPrintln are gone and the protocols have been renamed.

    class Foo: CustomStringConvertible, CustomDebugStringConvertible {
        var description: String {
            return "Foo"
        }
        var debugDescription: String {
            return "debug Foo"
        }
    }
    
    print(Foo())
    debugPrint(Foo())
    

提交回复
热议问题