快速关闭函数返回

时间:2019-08-30 08:33:34

标签: ios swift synchronization closures swift4

在检查Swift闭包内部的条件后如何从函数返回?从Swift闭包返回只是从闭包返回,而不是从函数返回。具体来说,我在Swift中使用了@synchronized的以下模拟:

    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
    }

然后在我的函数中:

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

     ...
     ...
    }

1 个答案:

答案 0 :(得分:3)

您将需要使用其他机制。也许退还一句,说你应该马上回来。

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 }

     ...
     ...
}