In the code below I create a function called startTimer. The purpose of this function is to count down from an input received by @IBAction. I am trying to understand:
Why do I need to declare a var secondsRemaining? Why do I need to use a self keyword to be able to refer to the
Full Code
import UIKit
class ViewController: UIViewController {
let eggTimes : [String : Int] = ["Soft": 300, "Medium": 420, "Hard": 720]
var secondsRemaining: Int? // self.secondsRemaining
@IBAction func hardnessSelected(_ sender: UIButton) {
let hardness = sender.currentTitle!
let timerSeconds = eggTimes[hardness]!
startTimer(secondsRemaining: timerSeconds)
//until here the code seems to work fine
func startTimer (secondsRemaining: Int?){
//create a function called startTimer which accepts an interger as argument called secondsremaining
self.secondsRemaining = secondsRemaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if self.secondsRemaining! > 0 {
//if the secondsRemaining >
print ("\(self.secondsRemaining ?? 0) seconds")
self.secondsRemaining! -= 1
}else {
Timer.invalidate()
}
}
}
//call the function start timer and give the secondRemaining argument the value of timerSeconds
}
Previous to this my function was like this
func startTimer (secondsRemaining: Int?){
//create a function called startTimer which accepts an interger as argument called secondsremaining
// self.secondsRemaining = secondsRemaining
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if secondsRemaining! > 0 {
//if the secondsRemaining >
print ("\(secondsRemaining ?? 0) seconds")
secondsRemaining! -= 1
}else {
Timer.invalidate()
}
}
}
Which would return me the error :
Left side of mutating operator isn't mutable: 'secondsRemaining' is a 'let' constant
This makes me ask two questions:
- Are all the arguments declared for functions always constants? If so, why
- If the answer to question 1 is No, how can I declare an argument as a variable in a function?