Hi everyone! We oftentimes need to assign some value to a variable only if it's not nil
, this leads to us having a code structured like this:
if let foo {
bar = foo
}
This is already pretty compact but I'm here to suggest an even shorter version to this:
bar = foo?
Similar to how Swift already has bar? = foo
to assign foo
if bar != nil
, code from my suggestion will assign foo
to bar
only if foo != nil
This can be expanded to another use case. Pretty often I find myself having a switch-case
statement that goes over an optional value, I'd suggest we use the same operator here to write this:
switch foo? {
...
}
Instead of this:
if let foo {
switch foo {
...
}
}
Or this:
switch foo {
...
case .none: break
}
This also would imply any optional value can be used there, so would also be a valid code:
foo = bar()? // bar() -> Optional<...>
foo = (try? bar())? // bar() throws -> ...
foo = (await bar())? // bar() async -> ...
However I'm not particularly fond of how the last 2 lines look like but, well, no one forces us to right such code
Thanks for having a look, I'd be glad to discuss it in detail