Created
December 24, 2023 17:02
-
-
Save simonbromberg/22711ddba8bcc19dcad6c2409e98e7af to your computer and use it in GitHub Desktop.
OptionalUnwrap
This file contains 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
public struct NilError: Error { | |
public let file: String | |
public let line: UInt | |
public let column: UInt | |
public let function: String | |
public init( | |
file: String = #fileID, | |
line: UInt = #line, | |
column: UInt = #column, | |
function: String = #function | |
) { | |
self.file = file | |
self.line = line | |
self.column = column | |
self.function = function | |
} | |
} | |
public extension Optional { | |
func unwrap( | |
file: String = #fileID, | |
line: UInt = #line, | |
column: UInt = #column, | |
function: String = #function | |
) throws -> Wrapped { | |
try unwrap( | |
or: NilError( | |
file: file, | |
line: line, | |
column: column, | |
function: function | |
) | |
) | |
} | |
func unwrap(or error: @autoclosure () -> Error) throws -> Wrapped { | |
switch self { | |
case let .some(w): return w | |
case .none: throw error() | |
} | |
} | |
@discardableResult | |
func unwrap<U>(_ transform: (Wrapped) throws -> U) rethrows -> U? { | |
try map(transform) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment