Check if the function was called?

How can I check if a function has been called? I created a function to see if the level was completed like this:

func levelOneCompleted(){

}

      

When the first bit is level, I call the levelOneCompleted () function.

Then the scene transitions to another scene. In this scene, I want to check if the function has been called. I think I can do some kind of "expression".

if levelOneCompleted is called {
//do this

else{

//do this
}

      

What would be the best way to do this?

+3


source to share


2 answers


Set boolean flag to true

inside levelOneCompleted()

:

var isLevelOneCompleted = false

func levelOneCompleted(){
    // do things...
    isLevelOneCompleted = true
}

      



And later ...

if isLevelOneCompleted {
    //do this
} else {
    //do this
}

      

+3


source


Swift 3 and Xcode 8.3.2

There are 2 tricks for this, here is the code:



// Async operation
func levelOneCompleted(completion: (_ completed: Bool) -> Void) {
    // do your function here
    completion(true)
}

// Here is how to use it
// than u can declare this in viewDidLoad or viewDidAppear, everywhere you name it
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // this is async operation
    levelOneCompleted { (completed) in
        if completed {
            print("levelOneCompleted is complete")
            // do something if levelOneCompleted is complete

            DispatchQueue.main.async {
                // Update your UI
            }
        } else {
            print("levelOneCompleted is not completee")
            // do something if levelOneCompleted is not complete

            DispatchQueue.main.async {
                // Update your UI or show an alert
            }
        }
    }
}


// Or u can use this code too, and this is Sync operation
var isLevelTwoCompleted: Bool = false
func levelOneCompleted() {
    // do your function here
    isLevelTwoCompleted = true
}


// to check it u can put this function everywhere you need it
if isLevelTwoCompleted {
    //do something if level two is complete
} else {
    //do something if level two is  not complete
}

      

+1


source







All Articles