New Convenient Behavior for Ternary Operator

I believe the primary issue with writing

value != nil ? self.useValue(value!) : self.doSomethingElse()

is the potential for a race condition. If value != nil evaluates to true, and then value is set to nil before self.useValue(value!) is evaluated, the code sample will trap.

I'm not 100% convinced an unwrapping shorthand is justified, but a warning if this anti-pattern is detected might be a good idea.


There has been some discussion in the past of more general 'pattern matching/binding expressions' which might also solve this issue along with others. One past thread I found was Unwrapping and value binding patterns in the condition of ternary expressions , but I'm pretty sure there have been others as well.

2 Likes