3

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"?
shallowThought
  • 19,212
  • 9
  • 65
  • 112
altralaser
  • 2,035
  • 5
  • 36
  • 55

2 Answers2

6

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.

Community
  • 1
  • 1
Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
  • I would err on the side of preferring `open`. You can't really forsee the cases in which other would want to subclass your classes. If there's no reason against it, there's no reason to not default to allowing it. – Alexander Jan 15 '17 at 07:33
  • Of course, there could be internal workings of your classes that you would like to be accessible to the public, but would not want over ridden (for example if the behaviour of these methods is crucial to the functioning of the class). Until such a situation arises, `open` is the way to go :) – Alexander Jan 15 '17 at 07:41
  • @Alexander Yeah, that's pretty much why I put it as `public` > `open` in the first place, but you're right that most of the time it's not necessary – Benjamin Lowry Jan 15 '17 at 07:42
2

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.

William
  • 271
  • 2
  • 10