Swift中的Public和Open有什么区别?

本文探讨了Swift中public和open关键字的区别,特别是在模块间重用和覆盖行为方面。通过实例,展示了如何使用open关键字允许其他模块重写库的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Today we’ll quickly explore the difference between the public and open keywords in Swift.

今天,我们将快速探索Swift中publicopen关键字之间的区别。

In short, we use open when we’re working on a module that at some point will be imported in a different module and overridden.

简而言之,当我们在某个模块上工作时,我们会使用open ,这有时会导入到另一个模块中并被覆盖。

For example, when you’re developing your own reusable UI element and want to distribute it using CocoaPods, you may consider using the open keyword to let others override the behavior of your library. With public, you may simply import the framework, but you can’t override it.

例如,当您开发自己的可重用UI元素并希望使用CocoaPods进行分发时,可以考虑使用open关键字让其他人重写您的库的行为。 使用public ,您可以简单地导入框架,但是不能覆盖它。

Without a further ado, let’s get started.

事不宜迟,让我们开始吧。

开始吧 (Let’s Start)

Say we’re creating our own UI element, and we want it to be reusable and independent. So we create a new target in our existing project, like so:

假设我们正在创建自己的UI元素,并且希望它可重用且独立。 因此,我们在现有项目中创建了一个新目标,如下所示:

Image for post

Next, we choose Static Library in the drop-down:

接下来,我们在下拉列表中选择“静态库”:

Image for post

We name it CircleView and create a simple rounded UIView:

我们将其命名为CircleView并创建一个简单的圆形UIView

Now let’s import it into our main project. First, we need to go to the Build Settings and add a dependency:

现在,将其导入到我们的主项目中。 首先,我们需要转到“构建设置”并添加一个依赖项:

Image for post

Finally, we’re able to add the CircleView in our main target’s files. Let’s now try to create a custom subclass in the CustomCircleView.swift file:

最后,我们可以在主要目标的文件中添加CircleView 。 现在,让我们尝试在CustomCircleView.swift文件中创建一个自定义子类:

We can see that we want to override the color property of the CircleView. However, the following errors pop up:

我们可以看到我们想覆盖CircleViewcolor属性。 但是,会弹出以下错误:

Image for post

As errors imply, we must mark the CircleView class and properties as open to be able to inherit from it and override its properties. Let’s modify the CircleView.swift file:

就像错误所暗示的那样,我们必须将CircleView类和属性标记为open ,以便能够从其继承并覆盖其属性。 让我们修改CircleView.swift文件:

Now if we return to the main target and build the project, we’ll see no errors.

现在,如果返回到主要目标并构建项目,则不会看到任何错误。

Note that we can’t mark structs as open; it only applies to classes and class members.

注意,我们不能将结构标记为open ; 它仅适用于班级和班级成员。

结语 (Wrapping Up)

Interested in other nuances of Swift? Feel free to check out my other relevant pieces:

对Swift的其他细微差别感兴趣吗? 随时查看我的其他相关文章:

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/better-programming/whats-the-difference-between-public-and-open-in-swift-945c845ab1bf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值