Swift: Weak, Unowned, Unsafe Unowned and Unowned Optional References

Swift uses reference types to manage memory, and it’s essential to choose the right variable reference type to prevent issues like retain cycles. Swift has different types of references, including strong, weak, unowned, unsafe unowned and unowned optional references.
Strong References:
Strong references are the only reference type that increases the reference count of an instance, and the instance can’t be deallocated unless the reference count is zero.
Weak References:
A weak reference in Swift doesn’t hold a strong reference to an instance. Even if an instance has weak references, it can be deallocated, and the variable holding the weak reference will be set to nil. Therefore, a variable initialized with a weak property is always an optional value, and it’s crucial to unwrap it before use or check for nil to avoid runtime crashes.
class ExampleClass {
weak var weakReference: ExampleClass?
}Unowned References:
Unowned references behave like weak references in that they don’t prevent the deallocation of an instance. However, unlike weak references, unowned references cannot be nil. If you try to access an unowned reference after the instance it refers to has been deallocated, it will result in an exception or a crash.
swiftCopy codeclass ExampleClass {
unowned var unownedReference: ExampleClass
}Unsafe Unowned References:
Unowned references are safe by default, but unsafe unowned references disable runtime safety checks. If you use an unsafe unowned reference after the instance is deallocated, it will lead to a dangling pointer with a garbage value, causing undefined behavior, weird output, or random crashes. Therefore, it’s crucial to use unsafe unowned references only when necessary, such as when interacting with low-level programming languages.
class ExampleClass {
// Unsafe unowned reference
unowned(unsafe) var unsafeUnownedReference: ExampleClass
}Unowned Optional References:
Unowned optional references are similar to normal unowned references but with the added flexibility of being optional. For example, in the code snippet below, the node class might or might not have a parent node, but if it did have a parent node, the parent should outlive the node. Therefore, we can use an optional unowned reference for the parent node variable in the node class.
class Node {
unowned var parent: Node?
}





