Swift从闭包中获取返回值并使用它从

时间:2017-08-22 21:43:48

标签: swift

请考虑以下事项:

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。我放置的内容boolmyClosure范围内,但filter中的封闭对此一无所知。如何从bool关闭中恢复filter的效果?感谢。

1 个答案:

答案 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所说,使用调度组异步执行此操作可能会更好。