iOS
SwiftUI
Incorrect/Unexpected Behavior
iOS 17.4 Seed 3 (21E5200d)
On device
- 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.
Demo | Workaround |
---|---|
![]() |
![]() |
AppleFeedback/FB13705289/demo.swift
Lines 1 to 37 in de5d7b8
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() | |
} |
AppleFeedback/FB13705289/workaround.swift
Lines 1 to 47 in de5d7b8
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() | |
} |