SwiftUI: How To Toggle a Switch Programmatically

November 10, 2025·1 min read·by dockui

SwiftUI: How To Toggle a Switch Programmatically

A programmatic toggle in SwiftUI means changing the Toggle value from code without the user tapping it.

Shortest Working Example

Code Snippet

This works because Toggle is bound to a @State Bool.
Changing that Bool updates the UI instantly.

Updating The Toggle From Another View

If the toggle is in another view, you pass a binding.

Code Snippet

Animate The Toggle Change

Code Snippet

SwiftUI will smoothly animate the change.

Common Mistakes

  • using let instead of @State
  • creating a new Bool each time instead of binding
  • not passing Binding when the toggle is in a child view

FAQ

Q: Can I programmatically toggle without a button?
A: Yes. You can flip the Bool anywhere in code: isOn.toggle()

Q: Does this work in macOS SwiftUI?
A: Yes. Same exact pattern.

Summary Code (Copy/Paste)

Code Snippet

Similar Blogs

View All Articles
SwiftUI: How To Reset a Form

SwiftUI: How To Reset a Form

Learn how to reset a SwiftUI form with one line. Clear text fields instantly using @State or a form model. Simple copy/paste SwiftUI code examples.

by dockui
Nov 10
How to use @AppStorage in SwiftUI

How to use @AppStorage in SwiftUI

Learn how to use @AppStorage in SwiftUI to save user settings and preferences easily with UserDefaults

by dockui
Oct 17
How to Make Text Selectable in SwiftUI

How to Make Text Selectable in SwiftUI

Learn how to make text selectable in SwiftUI using the .textSelection(.enabled) modifier. Enable text copying and selection easily in iOS 15 and later with

by dockui
Oct 13
How to Navigate to Another View in SwiftUI

How to Navigate to Another View in SwiftUI

Starting from iOS 16, Apple introduced the new NavigationStack API, which replaces NavigationView and makes navigation more powerful and reliable.

by dockui
Oct 13

Code copied to clipboard!