-
-
Save stephencelis/3a232a1b718bab0ae1127ebd5fcf6f97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 Good sleuthing :) My guess is Apple just hasn't used this API much, which is a shame, because it's really useful!
Thank you! Added a duplicate FB. I notice the custom solution in the episode suffers from a glitchy animation. At least it works, though. :)
@rayfix The episode code is simplified, but I believe swiftui-navigation handles animation correctly. It does so by writing through the binding's transaction:
(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
@stephencelis could be related to animations. Adding
.transition(.identity)
toToggle
prevents the crash for me.