Sobes.tech
Junior — Middle

What is the difference between declaring a class with the 'open' keyword and a regular class declaration without this modifier?

sobes.tech AI

Answer from AI

By default, all classes in Swift are closed for inheritance (final). This means that without the open or public modifier, a class cannot be inherited outside the module where it is declared.

  • A class declared with the open keyword can be inherited and overridden in any other module (for example, in another framework or application).
  • A class without the open modifier (usually public or no modifier) cannot be inherited outside the current module.

Thus, open is the most "open" access level for classes and their methods, allowing functionality to be extended in other modules.

Example:

open class OpenClass {
    open func doSomething() {}
}

public class PublicClass {
    public func doSomething() {}
}

// Inheriting from OpenClass in another module is possible
// Inheriting from PublicClass in another module is not possible