-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
        }
    }
didibobi
  • 13
  • 3
  • use a static variable in a function: https://stackoverflow.com/questions/25354882/static-function-variables-in-swift Then the function will remember the value of the variable. – Jerry Jeremiah Mar 07 '22 at 00: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. – Cristik Mar 07 '22 at 09: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... – Jerry Jeremiah Mar 07 '22 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. – Cristik Mar 08 '22 at 05:54

1 Answers1

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.

trndjc
  • 11,654
  • 3
  • 38
  • 51