vs 自定义调试模式
Custom debug descriptions can help you debug your own custom objects, structs, errors, and other types. Whenever you print out an object, you might end up with basic information that doesn’t really help you solve your issue. Printing out a struct shows you all the values, while you might only be interested in one of those properties in most cases.
自定义调试描述可以帮助您调试自己的自定义对象,结构,错误和其他类型。 每当您打印出对象时,最终可能会得到基本信息,这些信息并不能真正帮助您解决问题。 打印出一个结构会显示所有值,而在大多数情况下,您可能只对其中一个属性感兴趣。
Swift provides a default debugging textual representation for any type with the String(reflecting:)
initializer. The debugPrint(_:)
method is used for types that don't provide their own representation. Even though this already works great in most cases, you could benefit more and speed up debugging by implementing your own custom representation for types you often interact with.
Swift使用String(reflecting:)
初始化程序为任何类型提供默认的调试文本表示形式。 debugPrint(_:)
方法用于不提供其自身表示形式的类型。 尽管这在大多数情况下已经很好用,但您可以通过为经常与之交互的类型实现自己的自定义表示,从而从中受益并加速调试。
In this article, we’re making use of the print
and debugPrint
methods that are described in greater detail later on. Note that using po object
in an LLDB debug session aligns with using debugPrint
in code.
在本文中,我们将使用稍后将详细描述的print
和debugPrint
方法。 请注意,在LLDB调试会话中使用po object
与在代码中使用debugPrint
对齐。
Swift中提供的默认文本表示形式 (The Default Textual Representation Provided in Swift)
Before we start adding improvements, it’s good to know what Swift provides us with by default. For this, we’ll go over a few oft-used types and use the print()
and debugPrint
methods. These two print methods are almost the same, but the debugPrint
method allows you to optionally print out more verbose information. We'll go over a few examples later on.
在开始添加改进之前,最好先了解一下Swift为我们提供的功能。 为此,我们将介绍一些常用的类型,并使用print()
和debugPrint
方法。 这两种打印方法几乎相同,但是debugPrint
方法允许您有选择地打印出更多详细信息。 稍后我们将介绍一些示例。
We start the examples with the following BlogPost
entity that is defined as a class:
我们从以下定义为类的BlogPost
实体开始示例:
final class BlogPost {
let title: String
let body: String
init(title: String, body: String) {
self.title = title
self.body = body
}
}
Once we print this out, we get the following results:
一旦将其打印出来,我们将得到以下结果:
let blogPost = BlogPost(title: "Improved debugging", body: "Help yourself in those hard times.")
print(blogPost)
// Prints: BlogPost