Sobes.tech
Junior — Middle

Is it possible to create a weak reference to a property that implements a protocol?

sobes.tech AI

Answer from AI

In Swift, you cannot create a weak reference to a property that implements a protocol unless that protocol is class-only (restricted to class types). This is because weak references can only be applied to reference types (classes), and protocols can be adopted by structs and enums as well.

To use a weak reference to a property with a protocol type, you need to restrict the protocol to class types, for example:

protocol MyProtocol: AnyObject {
    func doSomething()
}

class MyClass: MyProtocol {
    func doSomething() {
        print("Doing something")
    }
}

class AnotherClass {
    weak var delegate: MyProtocol?
}

If the protocol is not restricted to AnyObject, then you cannot declare a weak reference, and you will need to use strong references or other memory management mechanisms.