-2

I've a function with if statement inside it, I want to check everytime person clicks, whenever the if statement returns true, I want that function to be removed or never again called, is it possible to achieve in swift?

    func checkLevelUp(){
        if CookieViewController.moneyLevel >= 3 && CookieViewController.bonusLevel >= 3 && CookieViewController.spinLevel >= 3 {
            print("Level up !!!!!!!") // if this is printed, I never want checkLevelUp function to exists
        }
    }
4
  • use a static variable in a function: stackoverflow.com/questions/25354882/… Then the function will remember the value of the variable. Commented Mar 7, 2022 at 0:26
  • @JerryJeremiah never, ever, should anyone recommend the usage of global variables to beginners. It creates the conditions for later subtle bugs that are not easy to find. Commented Mar 7, 2022 at 9:49
  • @Cristik a static local function variable isn't the same thing as a global variable. The scope is limited to the function. The posted answer (below) though... Commented Mar 7, 2022 at 20:12
  • @JerryJeremiah besides being not accessible from other places, a local static variable has the same downsides as the global ones. There are only a few valid reasons to have to resort to this kind of workaround, and the one in the question just doesn't qualify. Commented Mar 8, 2022 at 5:54

1 Answer 1

3

You need to store this particular state outside the scope of this function.

var didLevelUp = false

func checkLevelUp() {
    guard !didLevelUp else {
        return // return out of the function if `didLevelUp` is not false
    }
    if CookieViewController.moneyLevel >= 3 &&
        CookieViewController.bonusLevel >= 3 &&
        CookieViewController.spinLevel >= 3 {
        print("Level up !!!!!!!")
        didLevelUp = true
    }
}

How you store it outside the scope of the function is up to you but this is the solution you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.