Search code examples
swiftsegue

Checking Segue after it initiated


I have two UIViewController: A, B

Lets say there are two segues connecting them: C, D

Once a segue has been activated and I am in view B, can I know which segue got me here? C or D?


Solution

  • There is a prepare(for: segue) function that allows you to set a property in the new ViewController.

    class OriginViewController : UIViewController {
    
        ...
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destination = segue.destination as? SegueProtocol {
                destination.transitionSegue = segue.identifier
            }
        }
    }
    
    class DestinationViewController : UIViewController, SegueProtocol {
        var transitionSegue: String = ""
    
        override func viewDidLoad() {
            print("Segue: ", transitionSegue)
        }
    }
    
    protocol SegueProtocol {
        var transitionSegue : String { get set }
    }
    

    Edit: As per comment suggestion, it's better to expect a destination that conforms to a protocol rather than one of a specific type.