Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created June 15, 2021 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/e44ff1dc6d6a6b222e2130a1d14ddbf2 to your computer and use it in GitHub Desktop.
Save gordonbrander/e44ff1dc6d6a6b222e2130a1d14ddbf2 to your computer and use it in GitHub Desktop.
UnwrapOptional.swift
import Foundation
extension Optional {
struct NilError: Error {
let file: String
let line: Int
let column: Int
let function: String
}
/// Unwrap an optional, throwing a NilError if nil.
func unwrap(
file: String = #file,
line: Int = #line,
column: Int = #column,
function: String = #function
) throws -> Wrapped {
return try unwrap(
or: NilError(
file: file,
line: line,
column: column,
function: function
)
)
}
/// Unwrap an optional, throwing an error if nil.
func unwrap(or error: @autoclosure () -> Error) throws -> Wrapped {
switch self {
case .some(let value):
return value
case .none:
throw error()
}
}
}
extension Optional.NilError: LocalizedError {
public var errorDescription: String? {
"""
Failed to unwrap nil value (Optional.NilError)
File: \(self.file)
Line: \(self.line)
Column: \(self.column)
Function: \(self.function)
"""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment