Middle
How can you create a weak reference to a protocol type variable in Swift?
sobes.tech AI
Answer from AI
It is necessary to use the keyword weak before declaring a variable of protocol type. The protocol should be declared with the ability to apply only to classes: either inherit from AnyObject, or use the keyword class.
Example with inheritance from AnyObject:
protocol MyDelegate: AnyObject {
func doSomething()
}
class MyClass {
weak var delegate: MyDelegate?
}
Example with the keyword class:
protocol AnotherDelegate: class { // Before Swift 4.1
func doSomethingElse()
}
// In modern versions of Swift (>= 4.1), inheritance from AnyObject is sufficient
Using weak prevents strong reference cycles, for example, in delegation scenarios where the owner object references the delegate, and the delegate references back to the owner (or similar structure). A weak reference does not increase the reference count of the object.