Hello,
I'm a beginner with Swift and I'm struggling to understand the way the variables are send between class one and class two using protocol.
I want to create a data model for monitoring the heart rate. This data is displayed on the screen so that the user can see them. In parallel, it needs to check this data, i.e. print to the console what the label shows. I can not understand why the delegate property does not get a value (it has always nil) and why it does not print a phrase about what the user sees?
Technologies: XCODE Version 9.2, swift 4.
How can I solve this?
Thanks in advance.
CODE:
import UIKit
protocol HeartRateReceiverDelegate {
func heartRateUpdated(to bpm: Int)
}
class HeartRateReceiver {
var delegate: HeartRateReceiverDelegate?
var currentHR: Int? {
didSet {
if let currentHR = currentHR {
print("The most recent heart rate reading is \(currentHR).")
delegate?.heartRateUpdated(to: currentHR)
print("CurrentHR is \(currentHR)") // Check value
print("Delegate is \(delegate)") // Check value
} else {
print("Looks like we can't pick up a heart rate.")
}
}
}
func startHeartRateMonitoringExample() {
for _ in 1...10 {
let randomHR = 60 + Int(arc4random_uniform(UInt32(15)))
currentHR = randomHR
Thread.sleep(forTimeInterval: 2)
}
}
}
class HeartRateViewController: UIViewController, HeartRateReceiverDelegate {
var heartRateLabel: UILabel = UILabel()
func heartRateUpdated(to bpm: Int) {
heartRateLabel.text = String(bpm)
print("The user has been shown a heart rate of heartRateLabel.text")
}
}
let heartRateReceiver = HeartRateReceiver()
heartRateReceiver.startHeartRateMonitoringExample()
var heartRateViewController = HeartRateViewController()
heartRateReceiver.delegate = heartRateViewController