How is access to class objects and structure objects performed in Swift?
sobes.tech AI
Answer from AI
Objects of classes are accessed via references, while objects of structures are accessed via value.
Classes (reference type):
When assigning an instance of a class to a variable or constant, a reference to the same instance is assigned. Changes made through one reference will be reflected on all references pointing to that instance.
class MyClass {
var value: Int = 0
}
let object1 = MyClass() // Creating an instance
let object2 = object1 // object2 now points to the same instance
object1.value = 10 // Changing through object1
print(object2.value) // Will output 10 - change is visible through object2
Structures (value type):
When assigning an instance of a structure to a variable or constant, a copy of that instance is created. Each variable/constant contains its own independent copy of the data. Changes in one copy do not affect others.
struct MyStruct {
var value: Int = 0
}
var struct1 = MyStruct() // Creating an instance
var struct2 = struct1 // A copy of struct1 is created
struct1.value = 20 // Changing through struct1
print(struct2.value) // Will output 0 - struct2 remains unchanged
Comparison:
| Characteristic | Classes | Structures |
|---|---|---|
| Type | Reference | Value |
| Assignment | Copies the reference | Copies the value |
| Changes | Visible on all references | Affect only the copy |
| Inheritance | Supported | Not supported |
| Identity | Can be checked (===) |
No concept of identity |
The choice between class and structure depends on the requirements. Structures are often used for small, simple data types representing values (e.g., Point, Size, Range). Classes are used for more complex data types requiring reference semantics, inheritance, or object lifecycle management (e.g., UIViewController, UIView).