I'm going to take a stab at this even though this question has been around for a while because I think some example source code would be useful for understanding what init!
is for (at least it was for me).
An implicitly unwrapped optional provides two things of value:
- A convenience for the programmer (so you don't have to keep typing '
?
' at the end of your optional variables), and
- Runtime efficiency because it allows you to test an optional for
nil
only once, and thereafter (as long as it is non-nil
) use its unwrapped (i.e. direct) value.
The important part though is that an implicitly unwrapped optional is still an optional, which means it can be tested for nil
.
Now, as to the utility of the init!
-failable initializer, we can use it to get the two things I listed above (convenience and runtime efficiency), while still allowing an init
function to fail (i.e. to return nil
). This can happen, as others have noted, by calling into Objective-C API, but it can also happen directly from code you might choose to write. Here's an example:
class A {
init!() {
return nil // something happens that causes init to fail
}
}
var a:A! = A() // variable 'a' *is* an optional, and also nil
if a != nil { // and we can test it!
print( "a is not nil" )
} else {
print( "a is nil, better not use it." )
}
In this example, I gave myself a way to fail the initialization of class A
, and yes, could as easily have done it with an init?
method, but when I create an object of type A
I'll probably only ever need to test that the initialization succeeded or failed once--after all, I either created an A or I didn't--and afterwards if it's not nil
I'll just want to use the direct value. So in this case, using the init!
-failable initializer turns out to be pretty handy.