I have a View Controller that passes data to a second class. That class passes data to a third class. I am trying to use protocol and delegate to get information back to the original View Controller. However, I can't get that function to fire.
(VC -> Class 2 -> Class 3). That is the flow of data. What am I doing wrong?
Here is my code.
View Controller:
class ViewController: UIViewController, PostNumber {
func printNumber(number: Int) {
print("Number is \(number)")
}
override func viewDidLoad() {
super.viewDidLoad()
let thirdClass = ThirdClass()
thirdClass.delegate = self
let secondClass = SecondClass()
secondClass.addNumbers(firstNumber: 10, secondNumber: 5)
}
}
Second Class:
class SecondClass {
func addNumbers(firstNumber: Int, secondNumber: Int) {
let sum = firstNumber + secondNumber
let thirdClass = ThirdClass()
thirdClass.multiplyNumbersByTwo(number: sum)
}
}
Third Class:
protocol PostNumber {
func printNumber(number: Int)
}
class ThirdClass {
var delegate: PostNumber?
func multiplyNumbersByTwo(number: Int) {
let result = number * 2
print("test")
delegate?.printNumber(number: result)
}
}
You have to initialize ThirdClass on ViewController and then pass that into SecondClass. In the updated code below , the thirdClass instance is created in the ViewController, and the same instance is passed to the secondClass. This ensures that both classes are referring to the same instance of ThirdClass, allowing the delegate callback to work correctly.
View Controller:
class ViewController: UIViewController, PostNumber {
override func viewDidLoad() {
super.viewDidLoad()
let thirdClass = ThirdClass()
thirdClass.delegate = self
let secondClass = SecondClass()
secondClass.thirdClass = thirdClass
secondClass.addNumbers(firstNumber: 10, secondNumber: 5)
}
func printNumber(number: Int) {
print("Number is \(number)")
}
}
Second Class:
class SecondClass {
var thirdClass: ThirdClass?
func addNumbers(firstNumber: Int, secondNumber: Int) {
let sum = firstNumber + secondNumber
thirdClass?.multiplyNumbersByTwo(number: sum)
}
}
Third Class:
protocol PostNumber {
func printNumber(number: Int)
}
class ThirdClass {
var delegate: PostNumber?
func multiplyNumbersByTwo(number: Int) {
let result = number * 2
delegate?.printNumber(number: result)
}
}