Search code examples
iosswiftreturnguard

Run a function before hitting return. iOS, Swift,


Is there a way to run a function if a guard statment is not met before it gets to return?

guard let detectedRectangle = observations.first else { 

  functionToRun(completion: { (complete) in 

      print("Tony GOT TO RETURN"); return }
    })

The above code makes me put the return outside of the complete in part.

guard let detectedRectangle = observations.first else { 

  functionToRun(completion: { (complete) in 


    })

print("Tony GOT TO RETURN"); return } 

I have set 3 print statements in the function to run at certain points and it gets to 2 of them before hiting the return print


Solution

  • You can return functionToRun if the func, that contains guard statement, has same return type as functionToRun. Example:

    func guardHolder() { // guardHolder returns Void
        guard let detectedRectangle = observations.first else {
            // so, if functionToRun also returns Void type, we can return this func
            return functionToRun { _ in print("Tony GOT TO RETURN") }
        }
    }