Sharing Variables throughout the Application?

Hi All,

I am relatively new to the Swift language and need help understanding global variables and how to use them.

I am building an application which involves using several Views. I have a few variables which will need to seen in all Views, so I have created a Sift File called Global.

//
// Global.swift
// ServiceME
//
//
import SwiftUI
import Foundation

struct Global {
@State static var eMailAddress = ""
@State static var passWord = ""
}

The above shows how I have Declared the variables.
The following shit is showing how I am accessing and using the variables.

Do I have this right??

Pete

Putting aside global variables for a moment; you really do not want to be storing user credentials like that in an app. For security reasons. Some best practices are putting them in the user's keychain.

As for global variables; they need to be treated with caution. Shared mutable state is the cause of many bugs in applications.

Look up @EnviromentObject and @Enviroment for how to share common logic across views in SwiftUI,

3 Likes

Thanks Rob,

All noted.

Thanks for pointing me in the right direction.

Pete

1 Like

Pasting a picture of your code results in the use of significantly more energy for storage, retrieval and transport than for simple text. :slight_smile:

The code will be pretty printed, if you paste it between a pair of three backtick characters (```) like this:

```
Paste Code Here
```

For example:

func foo (u: String) async throws -> Int {
   print (#function, ":", u)
   // ...
   return 29
}

This will also make it possible for others to copy and compile your code.

Have a great day!

Thanks ibex10,

So much to learn :joy::joy:

Cheers.

1 Like