Where would I declare the variable total when I want it to be updated from within the functions but when the functions must run on page loading.

Take a look at the following code:

override func viewDidLoad() {                
     super.viewDidLoad()
            
     self.functionOne()
     self.functionTwo()
     self.printTotal()                
}
                            
var total = 0

func functionOne(){
      total += 1
}

func functionTwo(){        
    total += 1
}

func printTotal(){
    print(total)
}

Obviously I cannot declare the variable where it is at the moment, as the functions have already run by this point and the total would be set back to 0.

I also cannot move the variable declaration inside the function as that alters the scope and is no longer accessible to the other functions.

Furthermore I cannot declare the variable before the other functions run on page load because viewDidLoad() is a function in itself and therefore I could not access the variable from outside it.

The functions must run on page load as well, I cannot change that.

NB: I am not just trying to add two numbers together here, I know there are easier ways of doing that. This is just a grossly oversimplified example of the problem I am trying to overcome.

0

There are 0 best solutions below