Search code examples
swiftmodel-view-controllerseguecoupling

Are Swift segues closely coupled?


In Swift using MVC a common way to send data forward is to use prepare(for:sender:). Inside that method you get a reference to the destination VC and access its properties to send the data. But isn't that considered coupling the view controllers? I'm hoping the answer isn't considered a matter of opinion because I'd really like to understand how segues fit into MVC.


Solution

  • Passing data in a segue is completely compatible with MVC. The destinationVC is considered as a View of the sourceVC. When a controller communicates with a View, it configures the View with the data it needs. Writing to the public interface (properties) of the destinationVC is how you set it up. This is what is happening in prepare(for segue:sender).

    The concern about coupling relates to reuse. The more tightly coupled the viewControllers are, the harder it is to reuse them. This is only a problem if the destinationVC knows details of the sourceVC. If the destinationVC needs to pass data back to the sourceVC, it should do so using delegation (where a protocol is used to define the methods that the sourceVC implements).