I have the following unwrapping line in my code:
UIApplication.sharedApplication().openURL((NSURL(string: url)!))
Sometimes there occurs this fatal error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I know why this error sometimes occurs, but is there a way to make a try - catch statement around this line?
No, this is not what try and catch are for.
!
means "if this is nil, then crash." If you don't mean that, then don't use!
(hint: you very seldom want to use!
). Useif-let
orguard-let
:If you already have a
try
block and want to turn this situation into athrow
, that's whatguard-let
is ideal for: