How to distinguish the use of unowned without parameters from unowned(unsafe) in code?
sobes.tech AI
Answer from AI
In Swift, the keyword unowned is used to declare a weak reference that does not increase the reference count, with the assumption that the object will always exist during access.
-
unownedwithout parameters is a regular unsafe weak reference, which does not increase the reference count and is not optional. If the object has been deallocated, accessing this reference will cause a crash. -
unowned(unsafe)is a lower-level variant that does not check the validity of the reference at all. It means the reference points to memory that may have been deallocated, and accessing it is undefined behavior.
In practice:
class A {
var closure: (() -> Void)?
func setup() {
closure = { [unowned self] in
print(self)
}
}
}
Here, unowned guarantees that self exists during the closure call; otherwise, it crashes.
unowned(unsafe) is rarely used and only when you are sure of the object's lifecycle and want to avoid even minimal checks, for optimization.
Summary:
unowned— unsafe but checked at runtime (crash if accessed after deallocation).unowned(unsafe)— completely unsafe, no checks, can lead to undefined behavior.