Skip to content

Latest commit

 

History

History

FB13705289

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

Crash when projecting Binding to an unwrapped value

Basic Information

Which platform is most relevant for your report?

iOS

Which technology does your report involve?

SwiftUI

What type of feedback are you reporting?

Incorrect/Unexpected Behavior

What build does the issue occur on?

iOS 17.4 Seed 3 (21E5200d)

Where does the issue occur?

On device

Description

  • Run the given code.
  • Try out the picker to change the selection.
  • Press "Remove selection" to cause the crash.
  • I wouldn't expect this code to crash.

Evidence

Visual

Demo Workaround
Demo GIF Workaround GIF

Code

import SwiftUI
struct ContentView: View {
@State private var selection: Int?
var body: some View {
VStack {
Picker("Picker", selection: $selection) {
ForEach(0 ..< 3) { index in
Text("Index \(index)")
.tag(index as Int?)
}
}
.pickerStyle(.segmented)
Button("Remove selection") {
selection = nil
}
if let $selection = Binding($selection) {
OtherView(selection: $selection)
}
}
}
}
struct OtherView: View {
@Binding var selection: Int
var body: some View {
Text("Selection = \(selection)")
}
}
#Preview {
ContentView()
}

import SwiftUI
struct ContentView: View {
@State private var selection: Int?
var body: some View {
VStack {
Picker("Picker", selection: $selection) {
ForEach(0 ..< 3) { index in
Text("Index \(index)")
.tag(index as Int?)
}
}
.pickerStyle(.segmented)
Button("Remove selection") {
selection = nil
}
if let $selection = selectionBinding() {
OtherView(selection: $selection)
}
}
}
private func selectionBinding() -> Binding<Int>? {
guard selection != nil else {
return nil
}
return Binding(
get: { selection! },
set: { selection = $0 }
)
}
}
struct OtherView: View {
@Binding var selection: Int
var body: some View {
Text("Selection = \(selection)")
}
}
#Preview {
ContentView()
}