In Swift, value types — structures (struct) are emphasized as the primary tool for data modeling. Unlike Objective-C, where everything was objects (classes), Swift encourages the use of structures for simple models, data, and small business objects.
Many developers, especially those experienced in other object-oriented languages, mistakenly use classes for everything. This leads to memory issues (reference cycles), unexpected changes when passing objects, and complexities with thread safety, as classes are reference types.
Structures in Swift are value types; they are copied upon assignment and when passed to functions, unlike classes (reference types), which pass a reference. This makes structures preferable for models without complex lifecycle logic and inheritance.
Code example:
struct Point { var x: Int var y: Int } var p1 = Point(x: 10, y: 20) var p2 = p1 p2.x = 30 // p1.x remains 10
Key features:
Can a structure have a subclass?
No, structures in Swift do not support inheritance. Any extension of behavior is only possible through protocols and extensions.
Does this mean that structures are always copied when passed to a function?
In practice, Swift uses Copy-On-Write optimizations. If we do not modify the structure, it is not copied, and a copy is created only upon change. This applies to standard collections and complex structures.
var arr1 = [1, 2, 3] var arr2 = arr1 arr2.append(4) // Only here does the copying happen
In what cases should structures not be used?
Classes were used to store uniform data (for example, for points on a map), resulting in performance losses due to frequent memory access, complicated memory management, and bugs with mixed references.
Pros:
Cons:
Using structures for data models that copy safely, do not lead to leaks, and have no unnecessary complexity.
Pros:
Cons: