How to pass variables between .swift files.

Hi, I'm new in coding :),

I have a struct that contains variables in a .swift file.
I need these datas on another .swift file. How can I import them?

(They're on a SwiftUI based app)

I have this on the first .swift file
Code Block
  struct MyVariables {
static var infoProduct = ""
static var idProduct = ""
}
    

I have to use the infoProduct var on the other file

Thanks



Answered by OOPer in 650739022
In Swift, which file is not important (in most cases).
Please specify, which class or which struct. (Or something else?)

I have to use the infoProduct var on the other file

Please show the code in the other file.
Accepted Answer
In Swift, which file is not important (in most cases).
Please specify, which class or which struct. (Or something else?)

I have to use the infoProduct var on the other file

Please show the code in the other file.
First off, welcome to the world of coding!

It is tough to tell exactly the problem without more insight. By going off what you wrote, this structure may be within a class, therefore it is unreachable within another file unless you have an instance of that class.

There are a few options. The first being, make this structure global so it can be used everywhere. This is not good practice though. So the real solution is to design your code in a way that this structure is only accessible when needed.

Hopefully you can post more details about what you are trying to do so my answer can be a little more meaningful!
In SwiftUI, Environment var are a way to do this.

Currently, struggling on the same thing. Have you found a solution? If so, please let me know. :)

How to pass variables between .swift files.
 
 
Q