Swift delegate for a generic class

后端 未结 3 1378
爱一瞬间的悲伤
爱一瞬间的悲伤 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:45

    You can use templates methods with type erasure...

    protocol HeavyDelegate : class {
      func heavy(heavy: Heavy, shouldReturn: P) -> R
    }  
    
    class Heavy {
        typealias Param = P
        typealias Return = R
        weak var delegate : HeavyDelegate?  
        func inject(p : P) -> R? {  
            if delegate != nil {
                return delegate?.heavy(self, shouldReturn: p)
            }  
            return nil  
        }
        func callMe(r : Return) {
        }
    }
    class Delegate : HeavyDelegate {
        typealias H = Heavy<(Int, String), String>
    
        func heavy(heavy: Heavy, shouldReturn: P) -> R {
            let h = heavy as! H // Compile gives warning but still works!
            h.callMe("Hello")
            print("Invoked")
            return "Hello" as! R
        }  
    }
    
    let heavy = Heavy<(Int, String), String>()
    let delegate = Delegate()
    heavy.delegate = delegate
    heavy.inject((5, "alive"))
    

提交回复
热议问题