Created
June 15, 2021 13:51
-
-
Save gordonbrander/e44ff1dc6d6a6b222e2130a1d14ddbf2 to your computer and use it in GitHub Desktop.
UnwrapOptional.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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