0

I am trying to return a value from a function after executing a function that is not finishing immediately.

for example:

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
    }
}

The compiler is showing an error "Cannot convert value of type 'String' to closure result type Void". The closure inside notify can't return value to my outer function. Any ideas how to solve this issue?

Kevin
  • 1,103
  • 10
  • 33
  • Don't `return` as such, you are using an async call, why do you want to make it sync? Usually, that's bad idea. Are you sure about that? WHy not do `func yourFunc(completion: ((String) -> Void))` instead? What's the code calling for `returnSomeValue()`? – Larme Mar 30 '21 at 09:42
  • Technically, I think you can `group.wait()` rather than `group.notify`, but I don't think that is something you should do. – Sweeper Mar 30 '21 at 09:46
  • You are misusing `DispatchGroup`. It’s not designed for making **one** asynchronous task synchronous. – vadian Mar 30 '21 at 10:21

1 Answers1

4

Return inside the notify is void it's scope is different than the function , You need a completion

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")
    }
}

Or what is more common

func returnSomeValue(completion:@escaping((String) ->())) { 
    service.longTimeTofinish(onFinish: { completion("Returning some value as example") } )  
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87