Today we’ll quickly explore the difference between the public
and open
keywords in Swift.
今天,我们将快速探索Swift中public
和open
关键字之间的区别。
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元素,并且希望它可重用且独立。 因此,我们在现有项目中创建了一个新目标,如下所示:

Next, we choose Static Library in the drop-down:
接下来,我们在下拉列表中选择“静态库”:

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

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:
我们可以看到我们想覆盖CircleView
的color
属性。 但是,会弹出以下错误:

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!
谢谢阅读!