请考虑以下事项:
func myClosure(_ my_object: MyObject, completion: @escaping (Bool) -> Void) {
var bool: Bool
...
completion(bool)
}
let my_filtered_objects = my_objects.filter { obj in
myClosure(obj.id) { bool in
return bool // doesn't return from the filter closure
}
return true // returns from the filter closure
}
函数myClosure
的闭包捕获Bool
,我称之为bool
,我想使用bool
从闭包中返回filter
。我放置的内容bool
在myClosure
范围内,但filter
中的封闭对此一无所知。如何从bool
关闭中恢复filter
的效果?感谢。
答案 0 :(得分:8)
如果闭包是非逃逸的,这很容易:
let my_filtered_objects = my_objects.filter { obj in
var retVal = false
myClosure(obj.id) { bool in
retVal = bool
}
return retVal
}
对于转义闭包,您可能需要使用信号量来确保在函数返回时闭包已完成:
let my_filtered_objects = my_objects.filter { obj in
var retVal = false
let semaphore = DispathchSemaphore(value: 0)
myClosure(obj.id) { bool in
retVal = bool
semaphore.signal()
}
semaphore.wait()
return retVal
}
正如@Woof所说,使用调度组异步执行此操作可能会更好。