[Swift] Event notification by delegate

What to write in this article

Event notification by delegate in Swift Improve the code presented in the reference material to deepen your understanding

Purpose of writing this article

To check when you forget

What is "event notification"?

The object where the event occurs tells the event occurrence of another object.

Contents assumed this time

・ The staff measures the current temperature of a place. ・ Originally, it is easiest to understand how to write code like ①, but in order to understand "event notification by delegate", I dared to write code like ②.


staff.measureTemperature(at: place) //Output the result of measuring the current temperature


place.seach(by: staff) //Output the result of measuring the current temperature

What I did not consider in this code example

-Access modifier ・ Appropriate responsibilities of the class

Code example

protocol TemperatureMeasureDelgate:class{
    func willMeasureStart(at place:Place)
    func didMeasureEnd(at place:Place)
    func measure(at place:Place)
}

class TemperatureMeasure: TemperatureMeasureDelgate {
    func measure(at place: Place) {
        DispatchQueue.main.async {
            print("== measure function start  ==")
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 2){
            self.willMeasureStart(at: place)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 4){
            self.didMeasureEnd(at: place)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
            print("== measure function end ==")
        }
    }
    
    func willMeasureStart(at place:Place) {
        print("Start measuring degree at \(place.name)")
    }
    
    func didMeasureEnd(at place:Place) {
        print("Result: \(place.currentTemperature) degree")
    }
    
}

class Place {
    var delegate:TemperatureMeasureDelgate?
    var name:String
    var currentTemperature:Int
    
    init(name:String,currentTemperature:Int){
        self.name = name
        self.currentTemperature = currentTemperature
    }
    
    func seach(by staff:TemperatureMeasureDelgate?){
        self.delegate = staff
        delegate?.measure(at: self)
    }
}

var enoshima = Place(name: "Enoshima", currentTemperature: 30)
var staff = TemperatureMeasure()
enoshima.seach(by: staff)

Execution result

== measure function start  ==
Start measuring degree at Enoshima
Result: 30 degree
== measure function end ==

Reference material

Event notification in Swift (https://www.casleyconsulting.co.jp/blog/engineer/963/)

Recommended Posts

[Swift] Event notification by delegate
[Swift] Event notification pattern
[Swift] Loop pattern matching by case-let
[Swift] How to send a notification