【问题标题】:Swift closure return from functionSwift 闭包从函数返回
【发布时间】:2019-08-30 08:33:34
【问题描述】:

检查 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
        }
      }

     ...
     ...
    }

【问题讨论】:

标签: ios swift synchronization closures swift4


【解决方案1】:

您需要使用其他一些机制。也许返回一个 bool 表示您应该立即返回。

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 }

     ...
     ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多