UnwrapOrThrow

1.0.0

🎁 Unwrap an optional or throw an error if nil (or crash the program).
alexito4/UnwrapOrThrow

What's New

2022-01-03T19:54:33Z

Open source release.

Unwrap Or Throw (or Die!)

Build and Test

🎁 Unwrap an optional or throw an error if nil (or crash the program).

Not invented here. The idea for unwrap or die and unwrap or throw has been around in the Swift community for years. You can read all about it in the references below.

Usage

This library provides different facilities to unwrap an Optional .

Swift provides a way to go from a throwing function to an optional try? but it doesn't have an easy way to do the reverse operation.

Coalescing with raise

Swift's throw is not an expression so we can't use it on the right side of the coalescing operator ??. The raise function supplies this functionality. It’s a very simple function that throws the given error, but it makes it possible to use it in places where an expression is needed.

try someWork() ?? raise(YourError())

Coalescing with ??

An overload of ?? is provided to remove the need for the raise function. If you prefer to be succinct instead of explicit, you can just use an error on the right of the operator and it will just work.

try someWork() ?? YourError()

Method unwrapOrThrow

If you don't like to abuse the coalescing operator to throw errors, you can instead use a method variant.

try someWork().unwrapOrThrow(YourError())

The library comes with a default error: UnwrapError. So you can call the method without specifying a custom error.

try someWork().unwrapOrThrow()

☠️ Unwrapp or die

Despite the name of the library, you can also crash the program instead of throwing an error.

You can use the same techniques as when throwing errors but using fatalError("reason for crashing") instead:

try someWork() ?? raise(fatalError("reason for crashing"))

The compiler will show a warning on this line Will never be executed so instead of using raise you can directly fatalError on the right side of the ?? operator.

try someWork() ?? fatalError("reason for crashing")

Or if you prefer the method, you can also use it:

try someWork().unwrapOrThrow(fatalError("reason for crashing"))

This has the same result as force unwrapping ! but with a better error message to help you see the problems on the logs.

A barely use the unwrap or die since when I want to force unwrap I just do that and I don't find the lack of proper message an issue most of the time.

That's why I don't need to introduce a facility to just pass a reason String directly into the unwrap operation.

References

Author

Alejandro Martinez | https://alejandromp.com | @alexito4

Description

  • Swift Tools 5.5.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sun Oct 20 2024 08:19:41 GMT-0900 (Hawaii-Aleutian Daylight Time)