I dislike when I have to do this:
value != nil ? self.useValue(value!) : self.doSomethingElse()
I dislike it because the type system is powerful and helpful, and using ! means turning off the type system and just winging it. However, doing this within the type system takes up a completely unnecessary number of lines and just feels like too much boilerplate:
if let value = value {
self.useValue(value)
} else {
self.doSomethingElse()
}
For this use case, I think it would more elegant and expressive to be able to write:
value ? self.useValue(value) : self.doSomethingElse()
I am aware of and agree with the decision to not allow if optionalValue { }
, where an optional is used as a pseudo-boolean. What I'm proposing is that only with the ternary operator one is allowed to use an Optional
instead of a Bool
, and that in the affirmative half of the operator the name of the optional is shadowed by its unwrapped counterpart so it can be used without !
.
I think this may be less dangerous than allowing an optional in an if-statement and therefore may be approvable, but also my knowledge of the issue is limited, so more than approval of this idea I'm looking for an understanding of the potentially various reasons why something like this can't or won't be done. I'm guessing that one major hurdle to this concept is the idea of treating the affirmative half of the ternary operator as a distinct scope with different variable definitions. Perhaps the way the language is built makes this thoroughly impossible...
I do think the syntax lines up with the semantics quite nicely though, given that the optional to be potentially unwrapped is followed by a ?
. In the course of writing this post I'm realizing more and more that this would be such a usefully lightweight way to handle optional unwrapping. Is the main issue in terms of language design that someone might accidentally use a Bool?
, forgetting that it isn't a Bool
, and be expecting it to exhibit a behavior different to the reality?
Thanks for any responses.