The Architecture of Swift Objects
Swift is a multi-paradigm language, but its OOP capabilities are its backbone. Unlike Dart, where almost everything is an object (Reference Type), Swift leans heavily on Structs for data modeling. As an Architect, your first decision when creating a new model in the Revochamp iOS runner is choosing between a Struct and a Class.
- Classes vs. Structs: The Golden Rule
In Swift, Classes are Reference Types (shared instances), while Structs are Value Types (copied when passed around). Apple recommends using Structs by default and only using Classes when you specifically need inheritance or identity (e.g., a Database Manager or a UI Controller).
| Feature | Struct (Value) | Class (Reference) |
|---|---|---|
| Copying | Copy-on-assignment | Shared instance |
| Inheritance | No | Yes |
| Speed | Fast (Stack allocation) | Slower (Heap allocation) |
| Thread Safety | Safe (Unique copies) | Requires care (Shared state) |
| Initializers | Memberwise (Auto-generated) | Manual required |
- Defining a Class
Classes support inheritance, allowing one class to adopt the characteristics of another. This is identical to the 'extends' keyword in Dart.
- Protocols (Interfaces)
In Swift, we don't use 'Abstract Classes' to define contracts. Instead, we use Protocols. A protocol defines a blueprint of methods or properties that a class, struct, or enum must implement. This is the foundation of 'Protocol-Oriented Programming'.
- Encapsulation & Access Control
Swift provides granular control over who can see and modify your code. For an Engineering Manager, enforcing these is key to maintaining a clean API boundary.
- private: Visible only within the defining declaration.
- fileprivate: Visible within the entire file.
- internal (Default): Visible to the entire module (e.g., your iOS app target).
- public: Visible to other modules, but cannot be subclassed.
- open: Highest level; visible and can be subclassed by other modules.