Swift 等价于 Java toString() [英] Swift equivalent of Java toString()
问题描述
用于打印类实例状态的 Java toString()
的 Swift 等价物是什么?
What is the Swift equivalent of Java toString()
to print the state of a class instance?
推荐答案
description
属性正是您要寻找的.这是打印包含对象的变量时访问的属性.
The description
property is what you are looking for. This is the property that is accessed when you print a variable containing an object.
您可以通过采用协议 CustomStringConvertible
然后实现 description
属性,将 description
添加到您自己的类中.
You can add description
to your own classes by adopting the protocol CustomStringConvertible
and then implementing the description
property.
class MyClass: CustomStringConvertible {
var val = 17
public var description: String { return "MyClass: \(val)" }
}
let myobj = MyClass()
myobj.val = 12
print(myobj) // "MyClass: 12"
description
也用于调用 String
构造函数:
description
is also used when you call the String
constructor:
let str = String(myobj) // str == "MyClass: 12"
这是访问实例描述的推荐方法(与 myobj.description
相反,如果类没有实现 CustomStringConvertible
,它将不起作用)
This is the recommended method for accessing the instance description (as opposed to myobj.description
which will not work if a class doesn't implement CustomStringConvertible
)
这篇关于Swift 等价于 Java toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!