3 ms·
Swift’s `try` isn’t “real” exceptions. It’s basically syntax sugar around a Result type. You can convert them trivially: func someThrowingFunc() throws ->
by ninkendo 2y ago
Swift’s `try` isn’t “real” exceptions. It’s basically syntax sugar around a Result type. You can convert them trivially:
func someThrowingFunc() throws -> T
let someResult = Result(catching: { try someThrowingFunc() }) // someResult: Result<T, any Error>
Or the other way:
let someResultFunc() -> Result<T, any Error>
let t = try someResultFunc().get() // t: T
The reason I say they’re not “real” exceptions is that it compiles down to a branch that checks if a particular error return register is non-nil, same as you would with a result type. (As opposed to “real” exceptions like in C++ where execution is forcefully interrupted by an expensive exception handler.)
I started out in swift treating it like rust and using Result everywhere, and manually chaining results back up when I didn’t want to handle them, but after a while I realized that the `throws` and `try` statements were just way more readable syntax to accomplish the same thing I was already doing:
Want to “not care” about the thrown error? Use `try?`. Want to propagate it up? Use `try` and just mark your function as throws rather than explicitly returning a Result. Want to crash on an error? Use `try!`. Want to explicitly deal with the error? Use `catch`, or if you don’t like that syntax and you’d prefer matching on a success/error enum you can just convert it to a Result as I outlined above.