Skip to content

swift delegate

Published: at 11:53 AM | 1 min read
protocol ModelDelegate {
    func willValueChanged(curValue: Int, newValue: Int)
    func didValueChanged(curValue: Int, oldValue: Int)
}

class Model {
    var delegate: ModelDelegate?
    
    var count: Int = 0 {
        willSet {
            delegate?.willValueChanged(count, newValue: newValue)
        }
        didSet {
            delegate?.didValueChanged(count, oldValue: oldValue)
        }
    }
}

class View: ModelDelegate {
    func willValueChanged(curValue: Int, newValue: Int) {
        print("will, cur:\(curValue), new:\(newValue)")
    }
    
    func didValueChanged(curValue: Int, oldValue: Int) {
        print("did, cur:\(curValue), old:\(oldValue)")
    }
}

let model = Model()
let view = View()
model.delegate = view
model.count = 100
model.count = 200