Could it be that when using try?
(optional try) for the call of a throwing function with no return value the errors are just ignored?
func throwingVoidFunction() throws { . . . }
try? throwingVoidFunction()
I expected that the compiler does not allow a try?
in front of a throwing function with return type void
, but the compiler doesn't complain.
So is using try?
in front of a void function a way to absorb errors? (like when using an empty default catch: catch {}
)
There is no reason for the compiler to complain. The return type of
func throwingVoidFunction() throws { ... }
is Void
and therefore the type of the expression
try? throwingVoidFunction()
is Optional<Void>
, and its value is nil
(== Optional<Void>.none
) if an error was thrown while evaluating the expression,
and Optional<Void>.some()
otherwise.
You can ignore the return value or test it against nil
. An
example is given in An elegant way to ignore any errors thrown by a method:
let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With