I'm new to programming and today I've been researching Property Observers in Swift. This got me wondering if it would be possible to use one to trigger an app to change screens when the value of a variable reaches a certain point.
For example, let's say I have a game that uses the variable 'score' to save and load the user's score. Could I use willSet or didSet to trigger a change in views based on the fact that the score will reach a certain value?
What I was thinking was using something like this:
var maxscore : Int = 0 {
didSet{
if maxscore == 5{
switchScreen()
}}
}
... would call the switchScreen function. Should this work? I haven't been able to find any info on this, so don't know if that's because it's not possible or I just haven't found it.
But I have attempted this with no success. It all compiles and runs, but when the score hits that magic number of 5 nothing happens.
For the sake of completeness, my switchScreen function code is below:
func switchScreen() {
let mainStoryboard = UIStoryboard(name: "Storyboard", bundle: NSBundle.mainBundle())
let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("HelpScreenViewController") as UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
And the code I've used for setting the value to 5 is below:
func CheckAnswer( answerNumber : Int)
{
if(answerNumber == currentCorrectAnswerIndex)
{
// we have the correct answer
labelFeedback.text = "Correct!"
labelFeedback.textColor = UIColor.greenColor()
score = score + 1
labelScore.text = "Score: \(score)"
totalquestionsasked = totalquestionsasked + 1
labelTotalQuestionsAsked.text = "out of \(totalquestionsasked)"
if score == 5 { maxscore = 5}
// later we want to play a "correct" sound effect
PlaySoundCorrect()
}
else
{
// we have the wrong answer
labelFeedback.text = "Wrong!"
labelFeedback.textColor = UIColor.blackColor()
totalquestionsasked = totalquestionsasked + 1
labelTotalQuestionsAsked.text = "out of \(totalquestionsasked)"
if score == 5 { maxscore = 5}
// we want to play a "incorrect" sound effect
PlaySoundWrong()
}
SaveScore()
buttonNext.enabled = true
buttonNext.hidden = false
}