Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional try for function with no return value

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 {})

like image 604
user1364368 Avatar asked Jan 19 '17 20:01

user1364368


1 Answers

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)
like image 125
Martin R Avatar answered Oct 30 '22 08:10

Martin R