Swift 函数闭包 return
Swift closure return from function
如何在检查 Swift 闭包中的条件后从函数中 return? Return 来自 Swift 闭包只是 return 来自闭包,而不是函数。具体来说,我在 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
}
}
...
...
}
您需要使用其他一些机制。也许 return 一个傻瓜说你应该 return 马上。
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 }
...
...
}
如何在检查 Swift 闭包中的条件后从函数中 return? Return 来自 Swift 闭包只是 return 来自闭包,而不是函数。具体来说,我在 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
}
}
...
...
}
您需要使用其他一些机制。也许 return 一个傻瓜说你应该 return 马上。
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 }
...
...
}