s3协议和swift协议
The CustomStringConvertible
protocol becomes important when you need something to be printed out in the console. Remember, the print()
function is going to represent the textual form of the object in the console. However, this function has its own limitations and does not always work as you wish.
当您需要在控制台中打印出某些内容时, CustomStringConvertible
协议就变得很重要。 请记住, print()
函数将代表控制台中对象的文本形式。 但是,此功能有其自身的局限性,并不能始终如您所愿。
Let me clarify with an example. If you want to define a Car
class:
让我用一个例子来阐明。 如果要定义Car
类:
You can see the print
statement did not work properly. CustomStringConvertible
may be very useful in this situation, as it has one required computed property (description
) that returns a String
representation of the instance.
您可以看到print
语句不能正常工作。 CustomStringConvertible
在这种情况下可能非常有用,因为它具有一个必需的计算属性( description
),该属性返回实例的String
表示形式。
Without further ado, let’s explore CustomStringConvertible
in practice.
事不宜迟,让我们探索CustomStringConvertible
在实践中。
开始吧 (Let’s Start)
- Adopt the protocol by adding the colon and its name. 通过添加冒号及其名称来采用协议。
Conform to the protocol by adding the
description
computed property.通过添加
description
计算属性来符合协议。
Let’s consider the same previous example with a new protocol:
让我们考虑使用新协议的先前示例:
结语 (Wrapping Up)
This is all you should know about CustomStringConvertible
. I hope you found this interesting!
这就是您有关CustomStringConvertible
所有信息。 希望您发现这个有趣!
Interested in other relative protocols? Feel free to visit my other relevant articles:
对其他相关协议感兴趣吗? 随时访问我的其他相关文章:
If you have any criticism, question, or suggestion, feel free to post them in the comment section below!
如果您有任何批评,问题或建议,请随时在下面的评论部分中发表!
Thanks for reading.
谢谢阅读。
s3协议和swift协议