Some and None of Optional Optionals.

Prenez
VStackable
Published in
Oct 17, 2023

--

I came across this fun example of using Lists, Bindings and Optionals on X this morning.

Marcin Krzyzanowski opened a thread and asked why this wouldn’t work:

struct ContentView: View {
@State private var selection: Optional<Int> = 1

var body: some View {
List(selection: $selection) {
Text("1").tag(Optional(1)) // selection doesn't work
}
}
}

He received a reply back from James Pittman to the effect that .none represents no selection, and so has to represented. What works is this:

struct CompletionView_Yup: View {

@State private var selection: Optional<Optional<Int>> = .some(.some(1))


var body: some View {
List(selection: $selection) {
Text("None")
.tag(Optional<Int>.none)
Text("1")
.tag(Optional(1))
}
}
}

This works great. You can also do something like this:

 let x : Binding<Optional<Int>>? = .none
let x2: Binding<String>? = .none

Can you guess the syntax for assigning a .some(1) value in each case?

--

--

Prenez
VStackable

Writes iOS apps in Swift and stories in American English.