Event notification by delegate in Swift Improve the code presented in the reference material to deepen your understanding
To check when you forget
The object where the event occurs tells the event occurrence of another object.
・ 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
-Access modifier ・ Appropriate responsibilities of the class
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)
== measure function start ==
Start measuring degree at Enoshima
Result: 30 degree
== measure function end ==
Event notification in Swift (https://www.casleyconsulting.co.jp/blog/engineer/963/)