ExtensionOptional.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import Foundation
  2. import UIKit
  3. //func prepareImageForUpload(_ image: UIImage) throws -> UIImage {
  4. // return try watermark(image)
  5. // .flatMap(encrypt)
  6. // .orThrow(Error.preparationFailed)
  7. //}
  8. extension Optional {
  9. func orThrow(
  10. _ errorExpression: @autoclosure () -> Error
  11. ) throws -> Wrapped {
  12. guard let value = self else {
  13. throw errorExpression()
  14. }
  15. return value
  16. }
  17. }
  18. //let showInitialTutorial = completedTutorialSteps.isNilOrEmpty
  19. //let hasAddedFriends = !user.friends.isNilOrEmpty
  20. extension Optional where Wrapped: Collection {
  21. var isNilOrEmpty: Bool {
  22. return self?.isEmpty ?? true
  23. }
  24. }
  25. //let activeFriend = database.userRecord(withID: id)
  26. // .matching { $0.isFriend }
  27. // .matching { $0.isActive }
  28. //searchBar.text.matching { $0.count > 2 }
  29. // .map(performSearch)
  30. extension Optional {
  31. func matching(_ predicate: (Wrapped) -> Bool) -> Wrapped? {
  32. guard let value = self else {
  33. return nil
  34. }
  35. guard predicate(value) else {
  36. return nil
  37. }
  38. return value
  39. }
  40. }
  41. //let statusView = cell.accessoryView.get(orSet: TodoItemStatusView())
  42. //statusView.status = item.status
  43. extension Optional where Wrapped == UIView {
  44. mutating func get<T: UIView>(
  45. orSet expression: @autoclosure () -> T
  46. ) -> T {
  47. guard let view = self as? T else {
  48. let newView = expression()
  49. self = newView
  50. return newView
  51. }
  52. return view
  53. }
  54. }