Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created May 15, 2021 22:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ollieatkinson/8dd4d6826b3842df5a14d2ea41fde412 to your computer and use it in GitHub Desktop.
Save ollieatkinson/8dd4d6826b3842df5a14d2ea41fde412 to your computer and use it in GitHub Desktop.
Stringy Error
extension Optional {
public func or(throw error: @autoclosure () -> Error) throws -> Wrapped {
guard let wrapped = self else { throw error() }
return wrapped
}
}
extension String {
public func error(
_ function: String = #function,
_ file: String = #file,
_ line: Int = #line
) -> Error {
.init(message: self, function: function, file: file, line: line)
}
public struct Error: Swift.Error, CustomStringConvertible, CustomDebugStringConvertible {
let message: String
let function: String
let file: String
let line: Int
public var description: String { message }
public var debugDescription: String { "\(message) ← \(file)#\(line)" }
}
}
extension Error {
public var message: String { description }
}
@ollieatkinson
Copy link
Author

try dictionary[key.stringValue].or(throw: "No value found for key '\(key.stringValue)'".error())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment