Guest User

Untitled

a guest
Jan 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. /**
  2. * Require
  3. * Copyright (c) John Sundell 2017
  4. * Licensed under the MIT license. See LICENSE file.
  5. */
  6.  
  7. import Foundation
  8.  
  9. public extension Optional {
  10. /**
  11. * Require this optional to contain a non-nil value
  12. *
  13. * This method will either return the value that this optional contains, or trigger
  14. * a `preconditionFailure` with an error message containing debug information.
  15. *
  16. * - parameter hint: Optionally pass a hint that will get included in any error
  17. * message generated in case nil was found.
  18. *
  19. * - return: The value this optional contains.
  20. */
  21. func require(hint hintExpression: @autoclosure () -> String? = nil,
  22. file: StaticString = #file,
  23. line: UInt = #line) -> Wrapped {
  24. guard let unwrapped = self else {
  25. var message = "Required value was nil in \(file), at line \(line)"
  26.  
  27. if let hint = hintExpression() {
  28. message.append(". Debugging hint: \(hint)")
  29. }
  30.  
  31. #if !os(Linux)
  32. let exception = NSException(
  33. name: .invalidArgumentException,
  34. reason: message,
  35. userInfo: nil
  36. )
  37.  
  38. exception.raise()
  39. #endif
  40.  
  41. preconditionFailure(message)
  42. }
  43.  
  44. return unwrapped
  45. }
  46. }
Add Comment
Please, Sign In to add comment