Properties2
| Type | Concept |
| Note created | Feb 17, 2025 |
In Swift, you can define your own classes to take advantage of class inheritance in your application. Classes are also extensively used in SwiftUI to define elements of the graphical interface.
There are five key places where classes diverge from structs in Swift:
- You can make one class build upon the inherited functionality (or explicitly
overrideit). - Custom initializers are required for all classes (except if default values are provided for all properties).
- If you copy a class instance, both instances share the same data (the data is passed-by-reference).
- A special function called deinitializers can be called once the final instance of a class is destroyed.
- Doesn’t matter if a class instance is constant; if their properties have been defined as variable you can mutate them.
Syntax Considerations
Inheritance works by specifying an existing class name after a colon in the class definition.
class Employee {
let hours: Int
// ...
}
class Developer: Employee {
// ...
func work() {
print("Coding for \(hours) hours.")
}
}To override a function, it has to be explicitly stated using the override keyword. A class can be marked final if we want to prevent any other class inheriting from it.