Sobes.tech
Junior

What is the difference between a simple class and an open class in Swift?

sobes.tech AI

Answer from AI

By default, all classes in Swift are final — they cannot be inherited. To make a class inheritable, it must be declared as open or public, but there are important differences:

  • open — the most open access level. A class with the open modifier can be inherited and its methods overridden both within the module and outside of it.
  • public — the class is accessible outside the module, but inheriting it and overriding methods is only possible within the same module.

Thus, an open class allows extending and changing behavior in other modules, whereas a simple (e.g., public) class does not.

Example:

open class OpenClass {
    open func greet() {
        print("Hello from OpenClass")
    }
}

public class PublicClass {
    public func greet() {
        print("Hello from PublicClass")
    }
}

// In another module, you can inherit from OpenClass and override greet(),
// but not from PublicClass.
What is the difference between a simple class and an… - sobes.tech