【发布时间】: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