Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

A simple class (without an access modifier) has an internal access level by default. It can only be inherited within the same module (target).

An open class has the highest level of access and can be inherited and its members (methods, properties, subscripts) overridden both within the same module and in other modules (frameworks, libraries).

Modifier Inheritance within module Inheritance outside module Overriding members within module Overriding members outside module
internal (default) Yes No Yes No
open Yes Yes Yes Yes
// Example of a simple class (internal by default) WITHIN module A
class MyInternalClass {
    func internalMethod() {}
}

// Example of an open class WITHIN module A
open class MyOpenClass {
    open func openMethod() {}
}
// Usage WITHIN module A
class SubInternalClassInModuleA: MyInternalClass { // OK
    override func internalMethod() {}  // OK
}

class SubOpenClassInModuleA: MyOpenClass { // OK
    override func openMethod() {} // OK
}
// Usage OUTSIDE module A (for example, in module B)
// error: cannot inherit from non-open class 'MyInternalClass'
// class SubInternalClassInModuleB: MyInternalClass { }

class SubOpenClassInModuleB: MyOpenClass { // OK
    override func openMethod() {} // OK
}