Change what print(Object) displays in Swift 2.0

后端 未结 1 385
我在风中等你
我在风中等你 2021-02-14 16:51

I am trying to make my class Digit display the num variable whenever print is called on that object, in Swift 2.0. I thought this might be done with a

相关标签:
1条回答
  • 2021-02-14 17:27

    It isn't enough to just add a description variable. You need to also state that your class conforms to CustomStringConvertible (formerly known as Printable in earlier Swift versions).

    If you command click the print function, you find the following description.

    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.

    The part of which that matters here being that objects passed to print are not checked for whether or not they have a description method, but instead checked for things like whether or not the conform to protocols like CustomStringConvertible which offer data to be printed.

    That being said, all you need to do in this case is specify that your class conforms to CustomStringConvertible since you've already added a description variable. If you hadn't already added this, the compiler would complain because this protocol requires that the description variable be implemented.

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题