Home » Swift Variables

Swift variables

Variables are used to store data in memory so that we can use them in program. Variables are like container that can hold data which can be changed later. Every variable has a unique name called identifier.

How to declare Swift Variables?

In Swift 4, var keyword is used to declare variable.

Example:

Here, we have declared a variable named siteName of type String. It can hold only string values. If you execute the above code, it will give a compile time error because we have only declared variable and not assigned any value.

Let’s see how to assign values to a Swift variable.

How to assign values in Swift variable?

Assignement operator (=) is used to assign value in Swift variable.

Example:

Output:

tutoraspire.com   

Note: As, Swift is a type inferred language, it automatically knows “tutoraspire.com” is a String and declare siteName as a String. You can even remove the type (:String) from declaration and it will show the same result.

Example:

Output:

tutoraspire.com   

How to change the value of Swift Variable?

We can change the value of a variable by using assignement operator but without var keyword.

Example:

Output:

hindi100.com  

Print Current value of variables

We can use the print function to print the current value of variable or constant. Wrap the value in parenthesis with a backslash before the opening parenthesis.

Example:

Output:

The course duration of Java is 3 months.   

Next TopicSwift Constants

You may also like