5

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.

Jayesh Thanki
  • 1,879
  • 2
  • 21
  • 29
sandpat
  • 1,280
  • 9
  • 25

2 Answers2

4

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)
    }
  }
}
Mansi
  • 610
  • 8
  • 18
  • interesting! Thanks Mansi – sandpat May 10 '18 at 05:59
  • I guess this answered your question @Josh :) – Mansi May 10 '18 at 06:03
  • More or less Mansi, I have not tested it but it should work. Suppose we are on background thread. In that case, I will have to wrap guard inside DispatchQueue.main.async to be able to return like this. Now if I unwrap 'let statusCode = status' in guard statement, it won't be available below guard statement as guard is on the main thread. I don't want to do everything on main thread except UI changes. – sandpat May 10 '18 at 06:18
  • Nice Mansi, just unwrap your optional initViewcontroller in self?.present statement :) – sandpat May 10 '18 at 06:30
2

You can try out if statements

if let statusCode = status {
    //Success Block    
}
else{
    DispatchQueue.main.async() {
        let initViewController = self.storyboard!.instantiateViewController(withIdentifier: "SearchTabBarViewController")
        self.present(initViewController, animated: false, completion: nil)
    }
}

Many of us are familiar with Optional Binding and the “if let” syntax convention when unwrapping an optional value. The “if let” allows us to unwrap optional values safely only when there is a value, and if not, the code block will not run. Simply put, its focus is on the “true” condition when a value exists. Different from the “if let”, the “guard” statement makes early exits possible with an emphasis on negative cases with errors rather than on positive cases. This means we can test negative cases earlier by running the guard’s else statement if the condition is NOT met, rather than wait for nested conditions to pass first. read more with example

AshvinGudaliya
  • 2,696
  • 14
  • 29