I was continuing with @QuinceyMorris's example. Let me try to further clarify what I mean.
Assume a programmer writes this:
let x = optionalReturningFunc(/*args*/)
// Do some stuff
let y = optionalReturningFunc2(/*args*/)
// Do some more stuff
let z = optionalReturningFunc3(/*args*/)
// Do the rest of the stuff
Then the programmer types this, and compiler offers to insert !
for x
, y
and z
:
let t = function(x,y,z)
The programmer accepts compiler suggestion and it becomes:
let t = function(x!,y!,z!)
Then the programmer runs the code, and it stops with a runtime error on the above line. A novice programmer will have a hard time figuring out which one of x
, y
, z
or function
is causing the error.
Now imagine if the compiler went further and after the above fix-it was applied, generated a new warning suggesting the programmer move "I know it is not nil
" assertion where this assertion actually materializes here:
let x = optionalReturningFunc(/*args*/) // Warning: ...
The new warning could read something like this:
Warning: x
is asserted not-nil
at use site and is not checked or manipulated after this point.
With the following "fix it" suggestions:
- Put
!
after the function call to assert the function result can't benil
. - Put explicit optional type to silence this warning.
(It could go even further and suggest handling nil result withif let
orguard let
)
If the programmer accepts the first option, the code ultimately becomes:
let x = optionalReturningFunc(/*args*/)!
// Do some stuff
let y = optionalReturningFunc2(/*args*/)!
// Do some more stuff
let z = optionalReturningFunc3(/*args*/)!
// Do the rest of the stuff
let t = function(x,y,z)
This time, when the programmer runs the code, it fails on the declaration site of either x
, y
, or z
and our imaginary programmer will have a better idea what went wrong and probably add a check to see if the function actually returned a value.
We could go further and make things even more intelligent, but I hope you get the basic idea of putting assertions that programmer makes where the assertion actually materializes.