Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Last active June 30, 2020 12:42
Show Gist options
  • Select an option

  • Save mbrandonw/c5d1c43979054795a13c040dbc16d48f to your computer and use it in GitHub Desktop.

Select an option

Save mbrandonw/c5d1c43979054795a13c040dbc16d48f to your computer and use it in GitHub Desktop.
// This code has a bug. When you try to make a change to the selection
// it will not persist. The `selection` binding is never written to
// no matter what you do in the UI.
import SwiftUI
struct TestView: View {
@State var selection: Int?
var body: some View {
NavigationView {
Form {
Picker(selection: self.$selection, label: Text("Pick")) {
Text("None")
.tag(Int?.none)
ForEach(0...10, id: \.self) { int in
Text("\(int)")
.tag(int)
}
}
}
}
}
}
import PlaygroundSupport
PlaygroundPage.current.setLiveView(TestView())
// This fixes the bug described above
import SwiftUI
struct TestView: View {
@State var selection: Int?
var body: some View {
NavigationView {
Form {
Picker(selection: self.$selection, label: Text("Pick")) {
Text("None")
.tag(Int?.none)
ForEach(0...10, id: \.self) { int in
Text("\(int)")
- .tag(int)
+ .tag(Optional(int))
}
}
}
}
}
}
import PlaygroundSupport
PlaygroundPage.current.setLiveView(TestView())
@pcolton
Copy link

pcolton commented Jun 28, 2020

I think another option is that on line 15, explicitly define the parameter as an optional Int:

ForEach(0...10, id: \.self) { (int: Int?) in

@mbrandonw
Copy link
Author

@pcolton interesting! thanks for sharing that. that's good to know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment