Resolved: Insert "!" is a bad fixit

I strongly agree that inserting “!” Is a bad fixit. This was the most confusing thing about learning Swift for me when it was released.

At the same time, I think it’s a shame that adding yet another operator is the focus of the discussion here. Reading the evolution proposal I was struck by a couple of things that I found very confusing:

let something = array.last !! “Reason why Array isn’t empty”

And

let cast = xyz as? AnotherType !! “Here’s some text”

I find both cases confusing, especially from the perspective of a beginner. Where is the information as to what is optional in the array example? (What’d be worse is if this was not a standard library type where most experienced devs are aware what is optional). And where is the information as to why the second example should crash given the normally safe “?” in the second?

While I think this may be a “nifty” addition for people who know what’s going on here, in certain situations (not the ones above though!), this is just more noise and confusion amongst the sea of !s and ?s that seemingly motivated this proposal in the first place.

There have been some excellent suggestions above regarding improving the compiler diagnostics. One that seemed particularly helpful outlined:

  1. The name of the variable that has the optional type of Type?. If it’s not a variable, spelling out which function call or initialiser returns an optional result.
  2. Mentioning explicitly that its value can be nil and therefore needs to be unwrapped (possibly when it was created)
  3. Suggesting using if let, guard let, OR, asserting the value can never be nil by inserting ! either here or (in the case of a variable) when it was created.
  4. Alternatively adding ?? <> to provide a fallback value.

This is a very worthy topic but I really don’t think adding even more surface to the language does anything to help new users understand what’s happening here. Also as an experienced developer I can see situations (just two mentioned above) where !! significantly reduces code readability.

3 Likes