Skip to content

Instantly share code, notes, and snippets.

@stephencelis
Last active December 19, 2021 00:09
Show Gist options
  • Save stephencelis/3a232a1b718bab0ae1127ebd5fcf6f97 to your computer and use it in GitHub Desktop.
Save stephencelis/3a232a1b718bab0ae1127ebd5fcf6f97 to your computer and use it in GitHub Desktop.
// The `Binding.init?(_:)` is unsafe to use and can crash when state goes from non-`nil` to `nil`.
//
// To reproduce:
//
// * Paste this code over a fresh SwiftUI project's "ContentView.swift"
// * Run the preview or application
// * Tap "Bool?" to show the toggle
// * Tap "Bool?" again to try to hide it and the application will crash.
import SwiftUI
struct ContentView: View {
@State var bool: Bool?
var body: some View {
VStack {
Button("Bool?") {
self.bool = self.bool == nil ? false : nil
}
if let $bool = Binding(self.$bool) {
Toggle("Bool", isOn: $bool)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@iampatbrown
Copy link

@stephencelis could be related to animations. Adding .transition(.identity) to Toggle prevents the crash for me.

@stephencelis
Copy link
Author

@iampatbrown Good sleuthing :) My guess is Apple just hasn't used this API much, which is a shame, because it's really useful!

@rayfix
Copy link

rayfix commented Dec 18, 2021

Thank you! Added a duplicate FB. I notice the custom solution in the episode suffers from a glitchy animation. At least it works, though. :)

@stephencelis
Copy link
Author

@rayfix The episode code is simplified, but I believe swiftui-navigation handles animation correctly. It does so by writing through the binding's transaction:

https://github.com/pointfreeco/swiftui-navigation/blob/7a61fb419997f56bd9928c7b405fc7557a60d4bd/Sources/SwiftUINavigation/Binding.swift#L41

(Thanks to @iampatbrown for that particular solution to the problem!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment