pexels-photo-4974914.jpeg

Variables and @State

When coding we use variables as ‘placeholders’ for many different forms of data. Data can be Booleans ( True / False ), Integers, Strings and even Arrays which are ordered groups of Strings, Integers. 

Creating Variables

Firstly to create a variable one needs to write ‘var’ that denotes a variable that is being created. Then the variable needs to be given a name. For example if the variable is a name the variable could be called ‘Name’. Then the variable is given the data that it represents. See an example of a variable here:

var name = “Fred”

As mentioned the beginning part of the line of code, ‘var name’, tells the app that there is a new variable called ‘ name ’. The second part ‘ = “Fred” ’ refers to the data that is being assigned to the variable, in this case a String called ‘ Fred ‘.

Variable are created in the top part of the code between the Struct view and the Body View:

Using Variables

Once a variable has been created to recall the data all you need to do is refer to the variable name in the body of the app to show the data the variable refers too.

Var body: some view {
  Text(name)
}

Displays Fred within the App

Using @State to change variables

When using variables we usually are changing the data that is assigned to the variable. In the example above with the name we can create a simple Textfield and assign a name to the variable name ourselves when running the app rather than putting it in the code. 

We can’t simply change variables and display them because of the nature of the view in Swift. We will need to tell the app to refresh the view when the variable is changed and we do this by using @State before the variable when creating it.

This allows us to change the variable so it can be used and displayed even when changed. We can use it for example in a textfield to change the variable.

Textfield(“Placeholder”, text: $name)

We can then use the variable as before to recall the data from the textfield:

Text(name)

This will display whatever is entered in the textfield

Play around with variables and see what cool stuff you can do with them.

Leave a Comment

Your email address will not be published. Required fields are marked *