Skip to content

Instantly share code, notes, and snippets.

@ole
Last active November 9, 2023 13:47
Show Gist options
  • Save ole/a74b5db8bcd2522e0d98384f6032095a to your computer and use it in GitHub Desktop.
Save ole/a74b5db8bcd2522e0d98384f6032095a to your computer and use it in GitHub Desktop.
SwiftUI: Group { … }.task { … }
import SwiftUI
@main
struct GroupWithTaskApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State private var toggle: Bool = false
var body: some View {
Group {
if toggle {
Text("true")
} else {
Text("false")
}
}
.task {
print("Executing task")
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(1))
toggle.toggle()
print("Toggling to \(toggle)")
}
}
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment