swift 调试打印
In this article, we will learn how we can easily automate debugging Swift objects using a handy CustomStringConvertible
protocol conformance in an extension.
在本文中,我们将学习如何在扩展中使用便捷的CustomStringConvertible
协议一致性轻松地自动调试Swift对象。
The source code of the extension is available at the bottom of the article.
扩展的源代码在文章底部。
Without further ado, let’s get started.
事不宜迟,让我们开始吧。
开始吧 (Let’s Start)
If you have ever conformed to the CustomStringConvertible protocol, then this code looks very familiar to you:
如果您曾经遵守过CustomStringConvertible协议 ,那么您对以下代码非常熟悉:
If you have only two objects to debug, then it’s fine. But if you have many, creating similar looking description
properties for each object is going to be time consuming.
如果您只有两个要调试的对象,那很好。 但是,如果有很多对象,则为每个对象创建外观相似的description
属性将非常耗时。
For that reason, we can automate the process by creating an extension on the protocol so you will only need to conform to CustomStringConvertible
and the extension will do the heavy lifting for you.
因此,我们可以通过在协议上创建扩展来自动执行该过程,因此您只需要符合CustomStringConvertible
,扩展就可以为您完成繁重的工作。
Here is that extension:
这是扩展名:
Here is what it does:
这是它的作用:
- Create a string showing the type of an object 创建一个显示对象类型的字符串
Create a
Mirror
that is a representation of the object’s properties.创建一个代表对象属性的
Mirror
。- Iterate over the properties of the object and append the name and value of each property to the string. 遍历对象的属性,并将每个属性的名称和值附加到字符串中。
- Return the finished string 返回完成的字符串
As a result, the only thing you will now have to do is simply conform to the CustomStringConvertible
, no description
property is needed:
结果,您现在唯一要做的就是简单地符合CustomStringConvertible
,不需要description
属性:
Now, if we initialize a Message
with an Author
, then print it, we will see the following:
现在,如果我们使用Author
初始化Message
,然后打印它,我们将看到以下内容:
Great! We have successfully automated debugging Swift objects.
大! 我们已经成功地自动调试了Swift对象。
Sometimes you may want to provide a custom extension for each specific type. For example, your goal may be to print Codable
objects in one way and others differently. By using a type constraint (where Self: Codable
) it is easier than ever:
有时您可能想为每种特定类型提供自定义扩展。 例如,您的目标可能是以一种方式打印可Codable
对象,而以其他方式打印。 通过使用类型约束( where Self: Codable
),比以往任何时候都更容易:
Now this extension will work only for Codable
objects.
现在,此扩展名仅适用于Codable
对象。
资源资源 (Resources)
The source code of the extension is available in a Gist.
该扩展的源代码在Gist中可用。
结语 (Wrapping Up)
Want to learn more about cool Swift tricks? Check out my other stories below:
想更多地了解炫酷的Swift技巧? 在下面查看我的其他故事:
Thanks for reading!
谢谢阅读!
swift 调试打印