What is unowned in the context of Swift?
sobes.tech AI
Answer from AI
Unowned refers to automatic memory management in Swift (ARC). Unowned references are used to prevent strong reference cycles when two objects strongly reference each other. An unowned reference does not increase the reference count of the object. Unlike a weak reference, an unowned reference is expected to always point to an existing instance; if the instance it references is deallocated, accessing it will lead to a runtime error. It is used when the lifecycle of the related object either coincides with or exceeds the lifecycle of the object containing the unowned reference.
Example usage:
class Department {
var name: String
var courses: [Course] = []
init(name: String) {
self.name = name
print("\(name) department is being initialized")
}
deinit {
print("\(name) department is being deinitialized")
}
}
class Course {
var name: String
unowned var department: Department // Unowned weak reference
init(name: String, department: Department) {
self.name = name
self.department = department
print("\(name) course is being initialized")
}
deinit {
print("\(name) course is being deinitialized")
}
}
var accounting: Department? = Department(name: "Accounting")
var introToAccounting: Course? = Course(name: "Introduction to Accounting", department: accounting!)
accounting!.courses.append(introToAccounting!)
accounting = nil // Now the Department object can be deallocated
introToAccounting = nil // Now the Course object can be deallocated
In this example, Course has an unowned reference to Department. Since Course cannot exist without Department (logically), and Department manages the lifecycle of Course through the courses array, using unowned here is appropriate. This prevents a strong reference cycle between accounting and introToAccounting. When accounting becomes nil, the Department object is deallocated, and then the Course object is also deallocated because there are no more strong references to it.