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
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
}
}