Unwind UIViewController according to how it's displaying

Updated
Aug 15, 2021 8:41 AM
Created
May 27, 2021 4:54 AM
Tags
UIKit
Keywords
Date

extension UIViewController {

  /**
   [Experimental]
   Unwinds from this view controller according to how it's displaying.
   - pop
   - dismiss
   */
  public func _unwind(animated: Bool) {

    if let parent = parent {

      switch parent {
      case let navigationController as UINavigationController:
        if navigationController.viewControllers.last == self {
          navigationController.popViewController(animated: animated)
        } else {
          assertionFailure("Unsupported calling, `unwind` was called by a view controller that's not display as a top view controller.")
          navigationController.popViewController(animated: animated)
        }
      case _ as UITabBarController:
        assertionFailure("Unsupported")
      case _ as UIPageViewController:
        assertionFailure("Unsupported")
      default:
        parent._unwind(animated: animated)
      }

    } else {
      presentingViewController?.dismiss(animated: animated, completion: nil)
    }

  }

}