一般来说,开发中需要在控制台输出信息查看的时候,用到print
就可以
print("123") // 123
如果想让print
输出的东西能表现更多信息,就需要自定义输出了,那么就要保证实例遵守CustomStringConvertible
协议,就可以重写print
的description
描述
class Person: CustomStringConvertible {
var age = 0
var description: String {
"person_\(age)"
}
}
var p = Person()
print(p) // person_0
相应的,系统还提供了另外一个输出的协议CustomDebugStringConvertible
,对应着debugPrint
class Person: CustomDebugStringConvertible {
var age = 0
var debugDescription: String {
"person_debug_\(age)"
}
}
var p = Person()
debugPrint(p) // person_debug_0
基本上两个print
是没有什么区别的:
-
print
调用的是CustomStringConvertible
协议的description
-
debugPrint
、po
(控制台断点调试的时候,po
会优先调用debugPrint
)调用的是CustomDebugStringConvertible
协议的debugDescription
网友评论