Typed way to know all segues to/from a ViewController
I realized this need while doing some work on a unwind function, would be nice to have a way of knowing every time there is a new segue arriving there, like:
let typedSource = R.segue.viewControllerMain.arrivingSegues().source // or .partingSegues().destination
switch typedSource {
case .viewControllerStuff:
some.stuff()
case .viewControllerOtherStuff:
some.other.stuff()
}
So now I know if I add another unwind segue to this view controller. Obviously doesn't need to be exactly like that, but basically a way of learning that.
Interesting idea, but I think it needs some design. Some thoughts:
For unwind segues it looks like we don't know at compile time to what view controller we will unwind to. Runtime iOS will walk up the navigation stack looking for a view controller implementing the given selector, when found it will unwind to that controller. So I think that is something that we can't implement.
For "regular" segues it would be possible, I think you then would look something like:
let typedSegueEnum = R.segue.viewControllerMain.typeSegue(segue)
switch typesSegueEnum {
case .viewControllerStuff(let typedSegue):
typedSegue.destination.stuff()
case .viewControllerOtherStuff(let typedSegue):
typedSegue.destination.stuff()
}
This could be useful, because:
- The enum will change when you add segues, warning you when you forgot to handle it in the prepare method
- You write less code, since R.swift is figuring out what segue this is instead of the developer
Downside could be that you don't want to handle all the segues and that we need to determine what this method does if the given segue is not found.
But as I said interesting idea. Would love to hear more people about this, if they think this is useful for example.
If you don’t want to handle the segue having the case there with a break would make it clear that it’s intentional, and not that somebody just forgot to handle it.
What you mean if the segue is not found?
Yeah, agree, breaking is okay in that case, clearly shows intent.
If you call R.segue.viewControllerMain.typeSegue(segue) it could be that the given UISegue does not match any of the known segues for ViewControllerMain. This is probably a programmer error, but could occur. We could solve this by returning an optional or throwing an error for example.
Oh I see, I forgot that’s how the segues are handled, passing it as an argument, but yes probably an optional I would suggest logging something so the programmer know there is something wrong, but I don’t think that’s the behaviour in any other call right?