SALE: Save 50% on all my books and bundles >>

How to create constant bindings

Paul Hudson    @twostraws   

Fully updated for Xcode 11.4

When you’re prototyping some UI, or when you just need to pass in a value to give your SwiftUI preview something meaningful to show, you will find it useful to use constant bindings: hard-coded values that don’t change, but can still be used like regular bindings so your code works.

For example, if you want to create a toggle switch you would normally have to create an @State property to store the Boolean, then send that into the toggle switch when you create it. However, if you’re just prototyping your user interface you can use a constant binding instead, like this:

Toggle(isOn: .constant(true)) {
    Text("Show advanced options")

That switch is read-only and always on because that’s what our constant binding says, but it’s enough to get you moving for now – you can come back and replace it with a full @State property later.

These constant bindings come in all sorts of types: Booleans, strings, integers, and more are all available, and Swift will make sure you use the right one for each view type.

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred by integrating Instabug's SDK in one minute. You will automatically receive device data, network logs, and reproduction steps with every bug and crash report.

Learn more and get started for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Cascable unleashes the power of your camera and unlocks powerful workflows for shooting, managing, and geotagging your photos.

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.0/5