Middle
How can objects of classes be stored in an array by strong reference?
sobes.tech AI
Answer from AI
Objects of class type stored in an array by strong reference are stored by default in Swift if the array contains elements of class type. An array [MyClass] or Array<MyClass> will contain strong references to instances of MyClass.
Example:
class MyClass {
let id: Int
init(id: Int) {
self.id = id
print("MyClass \(id) created")
}
deinit {
print("MyClass \(id) deallocated")
}
}
var strongReferencesArray: [MyClass] = []
for i in 0..<3 {
let obj = MyClass(id: i)
strongReferencesArray.append(obj) // Array holds strong references
}
print("Array has \(strongReferencesArray.count) elements")
// Objects will not be deallocated as long as strong references exist in the array
// Assigning `nil` to the array or removing elements will lead to deallocation,
// if there are no other strong references.
// strongReferencesArray = [] // Example of releasing all strong references
// strongReferencesArray.remove(at: 0) // Example of releasing one strong reference
In Swift, value arrays (struct) or enumeration arrays (enum) store copies of their elements. However, if the array contains class instances (class), it stores strong references to those instances.