更改Swift 2.0中的print(Object)显示的内容 [英] Change what print(Object) displays in Swift 2.0
问题描述
在Swift 2.0中,每当在该对象上调用print时,我都试图使我的类Digit
显示num
变量.我认为这可以通过描述变量来完成,但是没有运气.
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 description variable, but no luck.
class Digit {
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
}
}
推荐答案
仅添加description
变量是不够的.您还需要声明您的类符合CustomStringConvertible
(在早期的Swift版本中以前称为Printable
).
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).
如果命令单击print
功能,则会找到以下说明.
If you command click the print
function, you find the following description.
写入
value
的文本表示形式和可选的换行符, 进入标准输出.
Writes the textual representation of
value
, and an optional newline, into the standard output.
使用value
协议从value
获取文本表示形式
符合性,按照以下优先顺序:Streamable
,
CustomStringConvertible
,CustomDebugStringConvertible
.如果没有
找到这些符合性后,将构建默认的文本表示形式
以实现定义的方式,基于类型,类型和结构.
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.
此处重要的部分是不检查传递给print
的对象是否具有description
方法,而是检查诸如是否符合CustomStringConvertible
协议之类的内容提供要打印的数据.
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.
也就是说,在这种情况下,您需要做的就是指定您的类符合CustomStringConvertible
,因为您已经添加了description
变量.如果尚未添加,则编译器会抱怨,因为此协议要求实现description
变量.
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
}
}
这篇关于更改Swift 2.0中的print(Object)显示的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!