Codementor Events

Should I use Segue to navigate controllers?

Published Apr 04, 2020

Many tutorials, iOS books for beginners teach us use Segue. That's good start. But is it good for you and your projects? From my experience, it's totally not good. Here the reasons.

1. It's slow

Storyboard is slow, especially you add many controllers in a Storyboard, that's a disaster. I wrote something about Storyboard here.

2. It's messy

When you have 4 or 5 controllers, yes, not too bad. When you have 10 controllers, and screen A can show screen B, C, D, screen B can show D and E, screen E can show A and C. It's a big pain in the ass.

3. You can't reuse your code

You have to open the storyboards, drag and drop segues many times. When you setup other segues, you have to set modalPresentationStyle again.

In other way, you can easily copy and paste the code.

let vc = DailyBonusController()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)

Simple? You can change to any controllers you want, instead of drag and drop to a controller, which located 3 or 4 screens from your current controller.

4. Typo mistakes

Segue identifier is a String, and you can easily have typo mistakes there. If your screens have many destinations, you have to if ... else to select what destination to process correct flow.

Notes:
If you have to use Segue, try to name identifier like "Show" + your_controller_name. By this way, you don't have to remember too many things anymore and prevent typo mistakes.

5. Sending data

When you use Segue, you send data to next screen in prepareForSegue.
Think this case, you have a UITableView or UICollectionView, selecting row/item shows detail screen. Here is how it works.

Use segue:

  • Save the selected IndexPath to a local variable.
  • Go to prepareForSegue and go to correct if case.
  • Unwrap selected indexpath.
  • Send data to your destination.

Don't use segue
In didSelectRow or somewhere you want to show.

  • Init the destination
  • Send data
  • Navigate.

And you can reuse this way in other places, just copy.

Conclusion

Just some reasons you shouldn't use segue. Hope this can help you find a better way in your code.

Enjoy coding.

Discover and read more posts from Ky Nguyen
get started
post commentsBe the first to share your opinion
Show more replies