Share variable data through View Controllers - Swift

Hi all,

I need to share the data of a String variable between two view controllers. VC1 defines the variable, and then VC2 needs to have the variable to be able to work with it later.

My current code is this:
VC1:
Code Block Swift
var myVariable: String = ""
...
let myVariable = array.randomElement()

VC2:
Code Block Swift
let firstVC = FirstViewController()
let myVariable = homeVC.myVariable
print("Data is \(myVariable)")

When called, VC2 prints:
Code Block text
Data is 

Is there anything I'm doing wrong? VC2 doesn't print the variable, even though VC1 is printing it before I tap the button to segue to VC2.

Any help would be appreciated - thank you all so much in advance!

You declare a var as a String.

Then you create a ne instance of myVariable. What is array ? Why do you redeclare it ? Where do you do it ?

In VC2, when you call line 2, you get the var which is "".

So, may be you just need to change line 3 in VC1 to (remove let)
Code Block
myVariable = array.randomElement()


Then you set the variable myVariable.

Is there anything I'm doing wrong? 

Yes, this line.
Code Block
let firstVC = FirstViewController()

With this line, you create a new instance of FirstViewController, which is not the same instance that set a random value to myVariable.

Generally, instantiating a view controller like let firstVC = FirstViewController() would not work as you expect.

The code shown has some other parts to be fixed. For example, in your line 3 of VC1, you need to remove let and unwrap the Optional returned from randomElement(). Also the line 2 of your VC2 should be let myVariable = firstVC.myVariable.


#1

You may need to access the right instance of your FirstViewController.
Maybe somewhere in your VC1, you need to pass self to the right instance of VC2.
How to fix depends on many things and I cannot show you just seeing a fragment of your code. (And the code with mistakes.)


#2

Another way, you can create a data store independent of VCs.
Code Block
class MyDataStore {
static let shared = MyDataStore()
var myVariable: String = ""
//You can have more, if you need...
//...
}

With this code, shared becomes the only instance of MyDataStore and you can access it from any VCs.

Example:

VC1

Code Block
MyDataStore.shared.myVariable = array.randomElement() ?? "*empty*"

VC2

Code Block
        let myVariable = MyDataStore.shared.myVariable
        print("Data is \(myVariable)")

This may also depends on other parts of your code.
If this does not work and you need something easily fit for your code, you need to show more context and the right code.
Share variable data through View Controllers - Swift
 
 
Q