swiftswift3watchkitwatchoswkinterfacecontroller

Passing data between two Interface Controllers


I want to pass a string between two Interface Controllers. On InterfaceController1 I want to create a variable like:

var level: String = ("easy")

And then be able to access that variable on InterfaceController2.

There is currently just one answer on Stack Overflow but it was created when Swift 1 was out and I can't find any up to date answers.

I would prefer not to use global variables as I am aware that they are not recommended.


Solution

  • The best way to achieve this without using a global or a singleton (which is essentially a global for this case) would be to use the delegate pattern. In InterfaceController2 create a delegate that's of type InterfaceController1 and set it when the InterfaceController2 gets displayed. Then when you need the value you can call InterfaceController1Delegate.level to access the value.

    You might be going about the problem wrongly though. From the sound of your names and values it seems like your holding state values for the app in the view controllers. If that's the case, I'd stick to a more MVC design and keep them in a state class or classes that get passed around or can be accessed from the various view controllers that might need them.