Sobes.tech
Junior — Middle

Kas saab luua nõrga viite omadusele, mis rakendab protokolli?

sobes.tech AI

Vastus AI-lt

In Swift, it is not possible to create a weak (weak) reference to a property that implements a protocol if that protocol is not limited to classes (class-only protocol). This is because weak references can only be applied to reference types (classes), while protocols can be implemented by both classes and structures or enumerations.

To use a weak reference to a property of protocol type, the protocol must be restricted by inheriting from AnyObject, 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 limited to AnyObject, then a weak reference cannot be created, and strong references or other memory management mechanisms must be used.