I think it's worth saying (or at least throwing out for dispute) that the fixit offering to add !
isn't of much value to anyone. For a beginner, it's often the wrong fix. For everyone, when it's actually the correct solution, applying the fixit is rarely faster than typing the single !
character.
(There are exceptions, of course. With a heavily parenthesized expression, for example, it can be awkward to see exactly where to put the !
.)
In terms of a better fixit, it seems at least possible that the compiler might distinguish between cases where the user explicitly called for an optional type:
let z = 1 as Int? // ok because of explicit cast to optional
let z: Int? = Int (exactly: 1) // ok because of type annotation
and cases where the optionality wasn't overt in the source code:
let x = 2 as? Int // implied cast to Int?, but not obviously to a newbie
let x = Int (exactly: 3) // return type is Int?
// assuming: let y: Int! = 4
let x = y // IUO implicitly becomes Int?
let x = z // already Int?, but unobviously due to lack of context
In these cases, if the variable is used where a non-optional is needed, it would be reasonable for the compiler to offer to add !
to the end of the RHS expression, or to wrap the declaration in guard let
or if let
. At the very least, the compiler should suggest changing the declaration to make x
non-optional, even if it can't provide a fixit.
Secondarily, it seems like it should be possible for the compiler to determine that a variable is always used with ?
or !
, and then provide a warning (and maybe a fixit) to suggest that the variable be made non-optional (thus cleaning up code that's already littered with !
and ?
). Ideally, there would be some flow analysis to see whether a nil
value is ever used (rather than being optional-chained or force-unwrapped out of existence).
This would be similar to the current message suggesting that an unmutated var
variable be changed to let
.