Reputation: 1564
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 {}
)
Upvotes: 7
Views: 2636
Reputation: 539815
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)
Upvotes: 6