What is the ‘open’ keyword for in Swift?
If you’re new to iOS / Swift development, you’ve possibly come across the open
keyword, only to ask yourself “What is this all about?”
Understanding the use of this strange keyword can potentially be confusing, however in this post I will try to cover a common use case and hopefully explain it’s purpose in modern Swift code.
What is it?
Introduced back in Swift 3, open
is a higher (more permissive) access level above public.
The access level of a type member is computed as the minimum of the true access level of the type and the declared access level of the member. If the class is public but the member is open, the true access level is public.
As an exception to this rule, the true access level of an open class that is a member of an public type is open.
Simply put it is “more public than public”.
But what could be more Public than Public? And Why?
As a language, Swift is committed to subclassing and overriding, it’s one of the core principles it is built on, however encouraging developers to invest in overridability when architecting a framework can come at a cost as designing a class for subclassing takes far more effort than just designing it for ordinary use.
Potentially another developer could come along and innocently change the behavior around how our class methods delegate to each other.
This has the danger of breaking subsequent subclasses that override those methods. Within a single module the danger of this is fairly negligible however across library boundaries this can become increasingly problematic.
This is where the open
keyword comes into play, it allows a developer to differentiate between public accessibility and public overridability, explicitly stating what is public for someone to use but not extend.
Let’s take the following pseudo code as an example
Should this class be declared in its own module, in this case let us imagine it is an authentication library, any other code attempting to subclass it would be able to inherit from Auth
because it has the open
keyword.
A child class could then override the login method as it is also marked with open
— notice however the resetPass
method is using the public
keyword instead. This explicitly sets the access level on this method as it can be called, but cannot be changed.
The open
keyword is an elegant and simple way of preventing developers accidentally overriding core functionality that is crucial to how your library works.
tl:dr?
- An
open
class is accessible and can be subclassed - An
open
class member is accessible and overridable - A
public
class is accessible but cannot be subclassed - A
public
class member is accessible but not overridable
Feel free to leave any questions in the comments below :)