在检查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
}
}
...
...
}发布于 2019-08-30 16:57:23
你需要使用一些其他的机制。或者回个布尔说你应该马上回去。
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 }
...
...
}https://stackoverflow.com/questions/57723269
复制相似问题