One of the most basic factors of any programming language are variables. Variables are stored information that can change. Variables come in many types, including arrays, integers, strings, and Boolean. This blog post is intended to discuss the basic and most common forms of variables.
Strings: This type of variable is very common and will be heavily used in Swift app programming. This type of variable stores text. For example you can have a String variable named currentUser and its value can be “John Doe”. You can call on the value of this variable when you need to access it. If the user changes, you can change the value of the variable. This type of variable can apply to many situations, not just users. The name of the variable can be anything you would like to call it. The value can be any form of text. The implementation of this type of variable is below. Please note that the implementation is different if you want to change the value of the variable after it has already been initialized.
// How to initialize the variable for the first time. var currentUser = "John Doe" // How to change the variable once it is already initialized. currentUser = "Sam Doe"
Integers: This is another very common form of variable in the Swift programming language. This type of variable stores a positive or negative number that is not a decimal. You can relate variables in swift to variables in Math.
One Example of an implementation of a variable is storing a user’s age. View the implementation below to implement the variable into your own code.
// How to initialize the variable for the first time. var usersAge = 9 // How to change the variable once it is already initialized. usersAge = 10
Boolean: These types of variables are fairly simple. Booleans store a value of either true or false. One example of implementation of this type of variable is when determining whether a user is eligible to use your app. These variables are also very useful for many other purposes. Please view the implementation below to implement this type of variable into your Swift app.
// How to initialize the variable for the first time. var usercanplay = false // How to change the variable once it is already initialized. usercanplay = true
Array: Arrays store an array of other variables. In other words, arrays store multiple of one type of variable. There can be an array of strings, integers, etc.. You can get an individual element of an array and even see how many elements are in an array. One use case of an array is to store users of your app.
// String Array var userArray = ["John", "Bob", "Fred"] //Get the first element of an Array userArray //This can be stored in a variable var cu = userArray //Please note that in Arrays the 0th value is the first value in the array, the 1st value is the second value and so on //Here is an Example of an Integer Array var agesArray = [21, 40, 5]