Sobes.tech
Middle+

How can you create a weak reference to a field that is a protocol?

sobes.tech AI

Answer from AI

You can use the keywords weak or unowned before declaring a protocol type property.

protocol MyProtocol: AnyObject { // The protocol must be limited to classes
    func doSomething()
}

class MyClass {
    weak var delegate: MyProtocol? // Weak reference to a property of type MyProtocol
    unowned var helper: MyProtocol // Unowned reference to a property of type MyProtocol (if you are sure the object always exists)
}

It is important to note that the protocol must be limited to classes (: AnyObject) to be able to use a weak or unowned reference. This guarantees that the type implementing the protocol is a reference type, not a value type.

The weak property of a protocol type is used when the object referenced by the property can be deallocated before the object containing this reference. If the referenced object is deallocated, the property automatically becomes nil.

unowned is used when you are sure that the object referenced by the property always has the same or a longer lifecycle than the object containing this reference. Using unowned is safe only if you guarantee the absence of cyclic references and are sure that the object pointed to by the property is always valid. If the object is deallocated and you try to access it through an unowned reference, a crash will occur.

In most cases, weak is used for delegates and other similar patterns.

How can you create a weak reference to a field that… - sobes.tech