Delegates in swift?

前端 未结 12 1612
天命终不由人
天命终不由人 2020-11-22 03:27

How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?

12条回答
  •  天命终不由人
    2020-11-22 04:08

    The solutions above seemed a little coupled and at the same time avoid reuse the same protocol in other controllers, that's why I've come with the solution that is more strong typed using generic type-erasure.

    @noreturn public func notImplemented(){
        fatalError("not implemented yet")
    }
    
    
    public protocol DataChangedProtocol: class{
        typealias DataType
    
        func onChange(t:DataType)
    }
    
    class AbstractDataChangedWrapper : DataChangedProtocol{
    
        func onChange(t: DataType) {
            notImplemented()
        }
    }
    
    
    class AnyDataChangedWrapper : AbstractDataChangedWrapper{
    
        var base: T
    
        init(_ base: T ){
            self.base = base
        }
    
        override func onChange(t: T.DataType) {
            base.onChange(t)
        }
    }
    
    
    class AnyDataChangedProtocol : DataChangedProtocol{
    
        var base: AbstractDataChangedWrapper
    
        init(_ s: S){
            self.base = AnyDataChangedWrapper(s)
        }
    
        func onChange(t: DataType) {
            base.onChange(t)
        }
    }
    
    
    
    class Source : DataChangedProtocol {
        func onChange(data: String) {
            print( "got new value \(data)" )
        }
    }
    
    
    class Target {
        var delegate: AnyDataChangedProtocol?
    
        func reportChange(data:String ){
            delegate?.onChange(data)
        }
    }
    
    
    var source = Source()
    var target = Target()
    
    target.delegate = AnyDataChangedProtocol(source)
    target.reportChange("newValue")    
    

    output: got new value newValue

提交回复
热议问题