Is there a better way to write "if let optionalValue = optionalValue { something = optionalValue }"? (Let us use _ with ? and ? ?)

I would love to be able to just say

something = optionalValue ?? _

or

optionalValue != nil ? doSomething() : _

It's not hard to read and would prevent clutter by eliminating lots of if check { ... }

Should this be submitted in Pitches?

Edit: Cannot seem to type "??" in the title (without an space.)

You could do it quick and dirty optionalValue.map { something = $0 }.

The "assign on .some" topic has been discussed at length and never got anywhere.

In your case, it looks like you're doing two things:

  • First, "re-assign on .some" (something = optionalValue ?? _) Use if let value = value { something = value }, which limits something reassignment to the optional value's .some case. The other approach right now is going to be something like: something = value ?? something. I don't know if the compiler is smart enough to catch and prevent assignment for nil. (or optionalValue.map { ...thing to do on some case ... }, which I don't really care for)

  • Second, (going by your example) conditionally perform a global function / closure on non-nil. For this, it's best to use an if-or-switch statement if let _ = optionalValue { doSomething() } or if optionalValue != nil { doSomething() }, etc. You can always use conditional chaining for methods, optionalValue?.doSomething(). In general, though, this kind of control statement feels like you're doing the wrong thing or solving the wrong problem because it feels so unnatural.

1 Like