Optional.swift 851 B

1234567891011121314151617181920212223242526272829
  1. import Foundation
  2. /// This extension allows us to call .orThrow() on optional types to convert them to a throwable.
  3. /// Heavily inspired by https://forums.swift.org/t/throw-on-nil/39970/7
  4. extension Optional {
  5. func orThrow(_ error: @autoclosure () -> Error) throws -> Wrapped {
  6. if let wrapped = self { return wrapped }
  7. throw error()
  8. }
  9. func orThrow() throws -> Wrapped {
  10. if let wrapped = self { return wrapped }
  11. throw NilError(msg: "Variable is nil, but should not be")
  12. }
  13. func orThrow(_ msg: String) throws -> Wrapped {
  14. if let wrapped = self { return wrapped }
  15. throw NilError(msg: msg)
  16. }
  17. func or(_ w: Wrapped) -> Wrapped {
  18. if let wrapped = self { return wrapped }
  19. return w
  20. }
  21. struct NilError: Error {
  22. var msg: String
  23. }
  24. }