您的位置:首页 > 移动开发 > Swift

swift协议接口建立链接_在Swift中创建自己的协议

2020-07-26 12:11 1381 查看

swift协议接口建立链接

To speak simply, a protocol is an interface that describes some properties and methods. Protocols allow developers to write flexible and extensible code in Swift without having to compromise the language’s expressiveness.

简单来说,协议是描述某些属性和方法的接口。 协议允许开发人员在Swift中编写灵活且可扩展的代码,而不必牺牲语言的表现力。

开始吧 (Let’s Start)

To create a protocol, use the protocol keyword followed by the name you want and defined by the curly braces. Protocols can be of 2 types: read-only/read-write. Read-only means you can only get the variable, but you cannot set it. Read-write means you can both set and get properties.

要创建协议,请使用protocol关键字,后跟所需的名称并由花括号定义。 协议可以有2种类型:只读/读写。 只读意味着您只能获取变量,但不能进行设置。 读写意味着您可以设置和获取属性。

Example of a protocol 协议示例

Then, adopt the protocol by adding a colon and appending the name of the protocol you want to adopt.

然后,通过添加冒号并附加要采用的协议名称来采用协议。

The compiler will automatically ask you to add all necessary requirements after you adopt the

FullName
protocol

在采用

FullName
协议后,编译器会自动要求您添加所有必要的要求

协议扩展 (Protocol Extensions)

Creating extensions to protocols are quite powerful feature that allows you to extend the protocol, without having to worry about breaking compatibility of existing code. By doing this, you can make some methods Optional or add a method for something individually.

创建协议扩展是一项非常强大的功能,可让您扩展协议,而不必担心破坏现有代码的兼容性。 这样,您可以使某些方法成为可选方法,或者为某些事物单独添加方法。

This extension makes a property to have a constant default String to the name you will add in the future.

此扩展名使属性具有一个常量默认字符串,该字符串为您将来添加的名称。

结语 (Wrapping up)

This is all you should know about Protocols and how to create them. I hope it was interesting!

这是您有关协议及其创建方法的全部知识。 我希望这很有趣!

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.

谢谢阅读。

翻译自: https://levelup.gitconnected.com/creating-your-own-protocols-in-swift-e266707892b7

swift协议接口建立链接

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: