Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS SwiftUI - Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type

Tags:

ios

swift

swiftui

TextField("search", text: $searchText)
    .accentColor(Color("ClickableLink"))
    .foregroundColor(.white)
    .focused($focusedField, equals: .field)
    .onAppear {
        self.focusedField = .field
    }
    .onSubmit {
        loadinglayout = true

        do {
            try await getMemes()
        }
        catch {
            print(error)
        }
    }

I get

"Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type"

inside onSubmit.

So far the

do 

method solved this kind of issues, why not here? I have absolutely no idea what else I could try

like image 507
user19559647 Avatar asked Sep 02 '25 16:09

user19559647


2 Answers

The problem is that you are trying to call an async method from a synchronous method. onSubmit is synchronous, while getMemes is async.

You need to wrap async methods in a Task if you want to call them from a synchronous context.

.onSubmit {
    loadinglayout = true
    Task {
        do {
            try await getMemes()
        }
        catch {
            print(error)
        }
    }
}                            
like image 127
Dávid Pásztor Avatar answered Sep 05 '25 02:09

Dávid Pásztor


If you are calling async function inside button

Button {
         Task{
               await fetchData()
             }
       } label: {
               Text("Refresh Time")
       }

it will wait for function to return data.

like image 21
Sheikh Wahab Mahmood Avatar answered Sep 05 '25 01:09

Sheikh Wahab Mahmood