Home > OS >  Swift Function return () but Value is something else ans existent
Swift Function return () but Value is something else ans existent

Time:06-26

I make an getData() call to Firebase. I am getting the right Value and I am storing it into a Variable (Ergebnis). The problem is, that I can't return the Value. I am getting the following error: Unexpected non-void return value in void function' How can I return it from the task?

func holDaten(Daten: String) async throws -> String{

    let ref = Database.database().reference()
    let kurstxt = UserDefaults.standard.value(forKey: "aktuellerKurs") as! String
    ref.child("\(kurstxt ?? "default value")/\(Daten ?? "")").getData(completion:  { error, snapshot in
        guard error == nil else {
            print(error!.localizedDescription)

            return;
        }
        let Ergebnis = Task{ () -> String in
            do{
                let Ergebnis =  await snapshot?.value as? String ?? "Unknown";
                return Ergebnis
            }
            catch{
                return("Nichts")
                print("Error")
            }
        }

        return Ergebnis
    })
}

CodePudding user response:

You will need to wrap your call to getData with withCheckedThrowingContinuation like this

func holDaten(daten: String) async throws -> String {
    let ref = Database.database().reference()
    let kurstxt = UserDefaults.standard.value(forKey: "aktuellerKurs") as! String
    return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<String, Error>) in
        ref.child("\(kurstxt ?? "default value")/\(daten ?? "")").getData { error, snapshot in
            guard error == nil else {
                print(error!.localizedDescription)
                continuation.resume(with: .failure(error))
                return
            }
            let ergebnis = snapshot?.value as? String ?? "Unknown"
            continuation.resume(with: .success(ergebnis))
        }
    }
}
  • Related