Swift delegate for a generic class

后端 未结 3 1413
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 09:23

I have a class that needs to call out to a delegate when one of its properties changes. Here are the simplified class and protocol for the delegate:

protocol MyC         


        
3条回答
  •  甜味超标
    2021-02-05 09:32

    Protocols can have type requirements but cannot be generic; and protocols with type requirements can be used as generic constraints, but they cannot be used to type values. Because of this, you won't be able to reference your protocol type from your generic class if you go this path.

    If your delegation protocol is very simple (like one or two methods), you can accept closures instead of a protocol object:

    class MyClass {
        var valueChanged: (MyClass) -> Void
    }
    
    class Delegate {
        func valueChanged(obj: MyClass) {
            print("object changed")
        }
    }
    
    let d = Delegate()
    let x = MyClass()
    x.valueChanged = d.valueChanged
    

    You can extend the concept to a struct holding a bunch of closures:

    class MyClass {
        var delegate: PseudoProtocol
    }
    
    struct PseudoProtocol {
        var valueWillChange: (MyClass) -> Bool
        var valueDidChange: (MyClass) -> Void
    }
    

    Be extra careful with memory management, though, because blocks have a strong reference to the object that they refer to. In contrast, delegates are typically weak references to avoid cycles.

提交回复
热议问题