Queryable Logo
Queryable

Asynchronous View Presentations in SwiftUI

View on GitHub

Turn this

ContentView.swift

struct ContentView: View {
@State private var isShowingConfirmationAlert = false
var body: some View {
Button("Do it!") {
isShowingConfirmationAlert = true
}
.alert(
"Really?",
isPresented: $isShowingConfirmationAlert
) {
Button("Yes") { confirmAction(true) }
Button("No") { confirmAction(false) }
} message: {}
}
@MainActor
private func confirmAction(_ isConfirmed: Bool) {
print(isConfirmed)
}
}

Into this

ContentView.swift

struct ContentView: View {
@Queryable<Void, Bool> var buttonConfirmation
var body: some View {
Button("Do it!", action: confirm)
.queryableAlert(
controlledBy: buttonConfirmation,
title: "Really?"
) { item, query in
Button("Yes") { query.answer(with: true) }
Button("No") { query.answer(with: false) }
} message: {_ in}
}
@MainActor
private func confirm() {
Task {
do {
let isConfirmed = try await buttonConfirmation.query()
print(isConfirmed)
} catch {}
}
}
}

Queryable is a property wrapper that can trigger a view presentation and await its completion from a single async function call, while fully hiding the state handling of the presented view.