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

Overview

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.

Read more: Unwrap Or Throw (or Die)

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()

☠️ Unwrap 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

You might also like...
ips2crash is a macOS command line too to convert a .ips file to a legacy .crash log file.

Synopsis ips2crash is a macOS command line too to convert a .ips file to a legacy .crash log file. Motivation It should be possible to read .ips file

The project used in the iOS Architect Crash Course lectures

iOS Architect Crash Course • August 2nd-8th • EssentialDeveloper.com https://www.essentialdeveloper.com/ios-architect-crash-course/aug-2021-a5220 It's

Create a weather app from scratch with this SwiftUI Crash Course
Create a weather app from scratch with this SwiftUI Crash Course

"Create a weather app from scratch with this SwiftUI Crash Course" https://youtu

Demo project of Swift language crash using Release build on iOS 14

Demo project of Swift language crash using Release build on iOS 14 Repro steps O

XCTestCrashDemo - XCTest Crash Demo with swift

XCTest Crash Demo This repo intends to centralize XCTest crash errors and the wa

An Xcode plugin for manually symbolicating crash logs
An Xcode plugin for manually symbolicating crash logs

CrashSymbal An Xcode plugin for manually symbolicating crash logs Install Build the project to install the plugin. The plugin gets installed in /Libra

🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0
🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0

Introduction 🏞 MediaBrowser can display one or more images or videos by providing either UIImage objects, PHAsset objects, or URLs to library assets,

A library that provides undo semantics for the Composable Architecture with optional bridging tofUndoManager.

Swift Composable Undo A library that provides undo semantics for the Composable Architecture with optional bridging with UndoManager. Motivation It is

An optional TextField Replacement for SwiftUI
An optional TextField Replacement for SwiftUI

TextInputView A TextField Replacement In his excellent YouTube tutorial series on Building SwiftUI Components, Peter Friese (@peterfriese on Twitter)

Swift µframework with extensions for the Optional Type

OptionalExtensions Why? Swift's Optional is pretty awesome, but it can always get better. This repository is an humble attempt to add some utility met

Complete Animated GIF Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling
Complete Animated GIF Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling

AnimatedGIFImageSerialization This library is no longer maintained. In iOS 13+ and macOS 10.15+, use CGAnimateImageAtURLWithBlock instead. AnimatedGIF

Swift optional desugaring

Swift optional desugaring Setup Make sure you have installed Swift according to the instructions from you earlier assignment. Open a terminal / consol

Thread -safe access to a lazily retrieved value, with optional validity checking

SerialUpdatingValue Thread-safe access to a lazily retrieved value, with optional validity checking Motivation Swift's Structured Concurrency provides

SwiftCheck is a testing library that automatically generates random data for testing of program properties

SwiftCheck QuickCheck for Swift. For those already familiar with the Haskell library, check out the source. For everybody else, see the Tutorial Playg

Swift program that creates ASCII art from an image
Swift program that creates ASCII art from an image

Swift ASCII Art Generator Converts an image to text for no good reason. The code is pretty cool, though. It's pure functional Swifty goodness. Take a

Memory leak when CoreML ML Program is runing on GPU

MLProgramMemoryLeak Every layer running on the GPU in ML Program will leak 912 bytes by MPSGraphEngine. This can easily lead to 200KB+ memory leak eve

A cli program written in swift (with async/await) that removes the unnecessary parts of xcframeworks.

xctrim A cli program written in swift (with async/await) that removes the unnecessary parts of xcframeworks. Usecase Say you downloaded firebase sdk a

Minimal AutoLayout convenience layer. Program constraints succinctly.

MiniLayout Minimal AutoLayout convenience layer. Program constraints succinctly. Usage Put label over textField // using MiniLayout: view.constrain(la

Releases(1.0.0)
Owner
Alejandro Martínez
Captain of the Mobile Team @workivate
Alejandro Martínez
Have you ever wanted to just throw your optional like a table?

JebStolem Have you ever wanted to just throw your optional like a table? Or mayb

Piotr Szadkowski 1 Feb 23, 2022
Throw common warnings of ViewController presentation as error.

SafePresentation Throw common warnings of ViewController presentation as error. Usage Replace present(_:_:_:) to throwingPresent(_:_:_:). let vc = Chi

noppefoxwolf 6 Jun 1, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
Observe objects in SwiftUI Views which may be nil

ObservedOptionalObject Rationale SwiftUIs @ObservedObject requires that the observed object actually exists. In some cases it's convenient to observe

Matthias Bartelmeß 7 Jul 20, 2022
Unwrap value from Dictionary in Swift

JHUnwrap Unwrap value from Dictionary in Swift Example let dict: Dictionary<String, Any> = [ "name": "Lilei", "age": 20, "

HaoCold 2 Dec 22, 2021
A library that adds a throwing unwrap operator in Swift.

ThrowingUnwrap A simple package to add a throwing unwrap operator (~!) to Optionals in Swift. Import Add this to the package-wide dependencies in Pack

Allotrope 3 Aug 27, 2022
In-App iOS Debugging Tool With Enhanced Logging, Networking Info, Crash reporting And More.

The debugger tool for iOS developer. Display logs, network request, device informations, crash logs while using the app. Easy accessible with its bubble head button ?? . Easy to integrate in any apps, to handle development or testing apps easier. First version, there is plenty of room for improvement.

Remi ROBERT 1.8k Dec 29, 2022
Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened his eyes

GodEye Automaticly display Log,Crash,Network,ANR,Leak,CPU,RAM,FPS,NetFlow,Folder and etc with one line of code based on Swift. Just like God opened hi

陈奕龙(子循) 3.7k Dec 23, 2022
Dotzu In-App iOS Debugging Tool With Enhanced Logging, Networking Info, Crash reporting And More.

Dotzu In-App iOS Debugging Tool With Enhanced Logging, Networking Info, Crash reporting And More. The debugger tool for iOS developer. Display logs, n

Remi ROBERT 1.8k Jan 3, 2023