Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand for guard return in swift?

Is there is a way to have guard automatically return without needing to actually write it out every single time, e.g:

guard let url = self.webView.url else { return }
guard let componentDict = URLComponents(string: url.absoluteString)?.dict else { return }
guard let id = componentDict["v"] else { return }
guard let idUrl = URL(string: baseUrl + id) else { return }

In the case where I actually need to do something in addition to return, I would include the else { return } bit with my extra handling.

Its not a huge bother, but it would be a nice thing to have.

like image 797
Geuis Avatar asked Feb 26 '18 03:02

Geuis


2 Answers

You could write that code using if let:

if let url = self.webView.url,
   let componentDict = URLComponents(string: url.absoluteString)?.dict,
   let id = componentDict["v"],
   idUrl = URL(string: baseUrl + id) {
   // do something with idURL
} else {
    return // if needed
}

But in short, no, you can't shorten an individual guard ... else { return }.

like image 33
rmaddy Avatar answered Oct 12 '22 08:10

rmaddy


guard statement is typed with else must be, there is no shortcut for this but you can use if..let to avoid else statement.

Or combine this related variables statement with single guard statement

   guard let url = webView.url,
         let componentDict = URLComponents(string: url.absoluteString)?.dict,
         let id = componentDict["v"],
         let idUrl = URL(string: baseUrl + id)
         else { return }
like image 145
Jaydeep Vora Avatar answered Oct 12 '22 08:10

Jaydeep Vora