Variables in Swift


A variable is used to store data that our program can manipulate and we can use it in our program to store useful information. You can think of a variable like a container that can store useful information.

In Swift, the data of a variable can be changed and each variable has a specific type. Every variable is declared with a unique name which is called an identifier.

Declare variable in Swift

In Swift programming, the var keyword is used to declare a variable. To assign value in the variable, the assignment operator (=) is used.

In the example given below, a variable is declared and then a value assigned in this variable:

var firstName:String
firstName = "Sasuke"
print(firstName)

Run this code online

Or

var firstName:String = "Sasuke"
print(firstName)

Run this code online

The output will be:

Sasuke

Swift language automatically knows the type of the variable even if you don’t mention the type. See the example by removing the type String from the above example and the result will be the same:

var firstName = "Sasuke"
print(firstName)

Run this code online

Output:

Sasuke

Syntax for variable declaration

var variableName = <initial value>

Syntax with the type annotation of the variable where the optional type has been declared:

var variableName:<data type> = <optional initial value>

How to change the value of a Swift Variable

The value of a variable in Swift can be changed. Below is an example where we are changing the value of a variable:

var firstName = "Sasuke"
print(firstName)
firstName = "Minato"
print(firstName)

Run this code online

Type of Swift Variable

Below are the types of Swift Variable

String

Represent a set of characters. String type variable stores textual data. For example:
“Hellow World”

Character

Represents a single character. It is a 16-bit Unicode character. Examples “r”, “s”.

Int or Uint

Represent an integer number. It is the whole number. An integer can be negative or positive.
Examples: 23, 4, -7, -54

You can specifically use Int32 to store 32 bit signed integers and Int64 to store 64 bit signed integer values. On the other hand, UInt32 and UInt64 store 32 and 64 bit unsigned integer values accordingly.

Float

Represent 32-bit floating-point number that is used to store small decimal values. For example, 3.456, 7.1283, -34.456

Double

Double type variables are used to store 64-bit floating-point numbers. It is required when the floating-point value is very large. For example: 5.736914293727

Bool

This type of variable stores boolean type of information that can be TRUE or FALSE.

You can print the current value of any Swift variable using the print function that is available in Swift. Below is the example where we are printing the current value of a variable:

var firstName = "Sasuke"
print("Here \(firstName) is a fictional character")

Output

Here Sasuke is a fictional character

Also, read: