Post

Replies

Boosts

Views

Activity

Safely converting optional state to non optional binding
Hi, How would we safely convert an optional state to a non optional binding variable? Using Binding<V?> to Binding<V>? with optional binding (if let) crashes if V is later set to nil. Below is a minimal reproducible example. import SwiftUI struct ChildView: View {   @Binding var nonOptional: String   var body: some View {     Text("text that does not use the binding variable")   } } struct ContentView: View {   @State var optional_: String? = "test"   var body: some View {     if let nonOptional = Binding($optional_) {       ChildView(nonOptional: nonOptional)       Button(action: {         optional_ = nil // crashes after tapping       }) {         Text("set to nil")       }     } else {       Text("text is nil")     }   } } Error: Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1ba385a30) in App.swift. I am not interested in using "" or other default values, since this only works well with strings, and misses the point of my question. Thanks.
1
1
3.1k
Nov ’22
@State not working on Swift Playgrounds
Hi, I'm trying to use SwiftUI on my iPad with Swift Playgrounds. The view below renders fine initially, but unfortunately the view does not update when @State changes, like it does on my Mac. In the little sidebar I can see the closure does get executed though... I'm using the newest non-beta version of everything. swift import SwiftUI import PlaygroundSupport struct ContentView: View {     @State private var tapCount = 0     var body: some View {         Button("Tap count: \(tapCount)") {             tapCount += 1         }     } } PlaygroundPage.current.setLiveView(ContentView()) Thanks.
1
0
1.8k
Apr ’21