1

How do I return from the function after checking a condition inside Swift closure? Return from Swift closure just returns from the closure, not the function. Specifically, I am using the following emulation of @synchronized in Swift:

    func synchronized(_ object: AnyObject, block: () -> Void) {
       objc_sync_enter(object)
       block()
       objc_sync_exit(object)
    }

    func synchronized<T>(_ object: AnyObject, block: () -> T) -> T {
       objc_sync_enter(object)
       let result: T = block()
       objc_sync_exit(object)
       return result
    }

And then inside my function:

  public func stopRunning() {
      synchronized( self ) {
        if status != .finished  {
            return;//<--Need to return from the function here, not just closure
        }
      }

     ...
     ...
    }
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131

1 Answers1

3

You'll need to use some other mechanism. Perhaps return a bool to say you should return straight away.

func synchronized(_ object: AnyObject, block: () -> Bool) -> Bool 
{
   objc_sync_enter(object)
   defer { objc_sync_exit(object) }
   return block() 
}

public func stopRunning() {
    guard synchronized( self, block: {
        if status != .finished  {
            return false//<--Need to return from the function here, not just closure
        }
        return true
      }) 
    else { return }

     ...
     ...
}

JeremyP
  • 84,577
  • 15
  • 123
  • 161