Skip to content

Instantly share code, notes, and snippets.

@stephencelis
Last active Dec 19, 2021
Embed
What would you like to do?
// 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

iampatbrown commented Oct 9, 2021

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

@stephencelis
Copy link
Author

stephencelis commented Oct 11, 2021

@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

stephencelis commented Dec 19, 2021

@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