Junior
Mis vahe on lihtsa klassi ja open klassi vahel Swiftis?
sobes.tech AI
Vastus AI-lt
In Swift, by default, all classes 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 marked withopencan be inherited, and its methods can be overridden both inside and outside the module.public— the class is accessible outside the module, but inheritance and method overriding are only possible within the same module.
Therefore, an open class allows extending and changing behavior in other modules, while 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, it is possible to inherit from OpenClass and override greet(),
// but not from PublicClass.