gpt4 book ai didi

xcode - Swift:协议(protocol)有真正的用途吗?

转载 作者:可可西里 更新时间:2023-11-01 00:53:31 30 4
gpt4 key购买 nike

我想知道为什么在 swift 中使用协议(protocol)。到目前为止,在每种情况下我都必须使用一个(UICollectionViewDelegate、UICollectionViewDataSource)我注意到它们甚至不必添加到类声明中我的代码就可以工作。他们所做的就是让你的类需要有特定的方法,这样它才能编译。打败我为什么这是有用的,而不是作为一个小便利贴来帮助你跟踪你的类(class)做了什么。

虽然我假设我错了。请有人愿意向我指出原因吗?

最佳答案

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol doesn’t actually provide an implementation for any of these requirements—it only describes what an implementation will look like.

所以它基本上是一个界面,对吗?

当你想为你的代码定义一个“契约”时,你可以使用一个接口(interface)。在大多数情况下,这样做的目的是启用该合约的多个实现。例如,您可以提供一个真实的实现和一个用于测试的假实现。

延伸阅读
Protocols
What is the point of an Interface?

关于xcode - Swift:协议(protocol)有真正的用途吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681766/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com