1

I'm trying to get a value received from an async closure and return it in a function with DispatchGroup however in the last part I get the error Cannot convert value of type 'String' to closure result type 'Void'

can anyone see the issue,

private func _pv(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String {
    
    let dispatchGroup = DispatchGroup()
    let dev = self.pickerDevices[row]
    let id = dev.internalUUID
    guard let name = dev.name
    else {
        return "\(id)"
    }
    dispatchGroup.enter()
    dev.adData.getMachineName { (mName) in
        print("machine name from wbmanager: \(mName)")
        self.coffeeMachineName = mName
        dispatchGroup.leave()
    }
    
    //Cannot convert value of type 'String' to closure result type 'Void'
    dispatchGroup.notify(queue: DispatchQueue.main) {
        return "\(name) \(self.coffeeMachineName)"
    }
}
akano1
  • 40,596
  • 19
  • 54
  • 67
  • You cannot return something from inside an asynchronous task, not even with `DispatchGroup`. And please drop the leading underscore in variables and functions. This is not Objective-C – vadian Mar 24 '21 at 09:48
  • You can't return for multiples reason (inside block where it's void return), but your main issue is about having an async call. – Larme Mar 24 '21 at 09:48
  • ok thanks, then how can I achieve this? I need to return a value from that function, and the way the value (mName) is obtained is through an async call. – akano1 Mar 24 '21 at 09:50
  • I'd prepare ALL the values first, and then reload the components. – Larme Mar 24 '21 at 09:51
  • Yes, performing a network operation in response to a request from a UI element for data is a bad idea. This sort of delegate function needs to be very responsive – Paulw11 Mar 24 '21 at 10:50

1 Answers1

0

You need

class ViewController: UIViewController {

    var coffeeMachineName = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        dev.adData.getMachineName { (mName) in
            print("machine name from wbmanager: \(mName)")
            self.coffeeMachineName = mName
            DispatchQueue.main.async {
                pickerView.reloadAllComponents()
            }
        }
        
     
    }
    
    private func _pv(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String {
        
         let dev = self.pickerDevices[row]
        let id = dev.internalUUID
        guard let name = dev.name
        else {
            return "\(id)"
        }
       return "\(name) \(self.coffeeMachineName)"
        
    }


}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87