altralaser
altralaser

Reputation: 2073

Using of "open" and "public"

I already read the documentation about the new modifiers "open" and "fileprivate". But there are two things that I don't understand:

  1. Why is it not possible to declare protocols or extensions also as "open"? And does it mean that it's not possible to use these things outside a module?
  2. If I don't want to build my classes for a module but an common app, should I declare my classes and methods as "open" anyway or is it good practice to keep them only "public"?

Upvotes: 3

Views: 4280

Answers (2)

William
William

Reputation: 271

open is for another module, for example in we use it in unit test or in cocoa pods, you can inherit from a pod (if it's: open class somePod {...}) or override some function (if it's: open func someFunctionInPod{...}) in your project.

Upvotes: 2

Benjamin Lowry
Benjamin Lowry

Reputation: 3789

As this answer says:

  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

I think the answer to your first question, is that you can't override or subclass a protocol or extension. Thus, there is no use for such things to be open because public already makes them accessible outside of a module.

For your second question, I would say that you should only declare your own classes as open if you plan on overriding or subclassing. Otherwise you are allowing unnecessary access to these items. Most of the time public should suit your needs.

Edit:

As @Alex points out, I don't think there are many downsides to allowing this "extra access". The only thing I can think of is if you just wanted to protect your classes from your future self, but that may or may not be applicable. Thus, if this is not the case, there shouldn't be much harm in setting them as open by default.

Upvotes: 6

Related Questions