How can I change the textual representation displayed for a type in Swift?

后端 未结 6 926
广开言路
广开言路 2020-11-29 21:07

How can I modify the textual output that gets displayed in string interpolation?

The Printable protocol looks the most obvious but it\'s ignored in both

6条回答
  •  心在旅途
    2020-11-29 21:14

    Relevant Apple Swift Docs

    Apple provides this example:

    struct MyType: Printable {
        var name = "Untitled"
        var description: String {
            return "MyType: \(name)"
        }
    }
    
    let value = MyType()
    println("Created a \(value)")
    // prints "Created a MyType: Untitled"
    

    If you try this in playground, you will get the same issue that you're getting (V11lldb_expr...). In playground, you get the description on the right hand side when you call the initializer, but the println doesn't return something legible.

    Out of playground, however, this code behaves as you would expect. Both your code and the sample code from Apple above print the correct description when used in a non-playground context.

    I don't think you can change this behavior in playground. It could also just be a bug.

    EDIT: I'm pretty sure that this is a bug; I submitted a bug report to Apple.

    UPDATE: In Swift 2, instead of Printable, use CustomStringConvertible (relevant doc link).

    struct MyType: CustomStringConvertible {
        var name = "Untitled"
        var description: String {
            return "MyType: \(name)"
        }
    }
    
    let value = MyType()
    println("Created a \(value)")
    // prints "Created a MyType: Untitled"
    

提交回复
热议问题