Swift 从调度组通知内的函数返回值

Kev*_*vin 1 swift

我试图在执行未立即完成的函数后从函数返回一个值。

例如:

func returnSomeValue() -> String {
    let group = DispatchGroup()
    group.enter()
    service.longTimeTofinish(onFinish: { group.leave() } ) // <-- this function takes long time to finish

    group.notify(queue: .main) {
        return "Returning some value as example" // <-- Here is the issue
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器显示错误“无法将类型‘String’的值转换为闭包结果类型 Void”。通知内部的闭包无法将值返回给我的外部函数。有什么想法如何解决这个问题吗?

Sh_*_*han 5

Return 里面的notifyvoid的范围与函数不同,你需要一个完成

func returnSomeValue(completion:@escaping((String) -> ())) {
    let group = DispatchGroup()
    group.enter()
    service.longTimeTofinish(onFinish: { group.leave() } ) // <-- this function takes long time to finish

    group.notify(queue: .main) {
        completion("Returning some value as example")
    }
}
Run Code Online (Sandbox Code Playgroud)

或者说还有什么比较常见的

func returnSomeValue(completion:@escaping((String) ->())) { 
    service.longTimeTofinish(onFinish: { completion("Returning some value as example") } )  
}
Run Code Online (Sandbox Code Playgroud)