Search code examples
iosswiftguardpresentviewcontroller

Present a ViewController inside guard statement swift


I am trying to present a viewcontroller in case, status (an Int?) is nil as follows:

    guard let statusCode = status else {
        DispatchQueue.main.async() {
            let initViewController = self.storyboard!.instantiateViewController(withIdentifier: "SignInViewController")
            self.present(initViewController, animated: false, completion: nil)
        }
            return
    }

I want to know if this is the best practice because return after presenting a viewcontroller doesn't make much of a sense but it is required in guard statement as guard statement must not fall through.


Solution

  • To answer your question regarding guard statement and return keyword

    func yourFunc() {
        guard let statusCode = status else {
          return DispatchQueue.main.async() { [weak self] _ in
            let initViewController = self?.storyboard!.instantiateViewController(withIdentifier: "SignInViewController")
            self?.present(initViewController!, animated: false, completion: nil)
        }
      }
    }