Swift: Variables

Variables in Swift:

Let’s begin with Variables in Swift.


Because a variable is a memory location in the computer in Swift. So, we can use it to store, retrieve, and manipulate data.

var grade = 0


Constants are fixed values that a program can’t alter while it’s executing. Hence the let keyword can be used to declare one.

let pi = 3.14

Arithmetic Operators:

The following arithmetic operators of Swift are as follows:

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % remainder
var a = 0
a = 6 + 2  // a is now 8
a = 6 - 2  // a is now 4
a = 6 * 2  // a is now 12
a = 6 / 2  // a is now 3
a = 6 % 2  // a is now 0


A type annotation explicitly specifies the type of a variable or expression in Swift. So, type annotations begin with a colon ( : ) and end with a type. We can use type annotation during declaration.

The following are the basic data types:

  • Int: integer numbers
  • Double: floating-point numbers
  • String: a sequence of characters
  • Bool: truth values, Hence true or false.
var score: Int = 98
var pi: Double = 3.14
var greeting: String = "Welcome to Swift"
var flag: Bool = false

String Interpolation:

By including their values inside a string literal, string interpolation can be used to construct a String from a mix of variables, constants, and others. For example: the code given showing the string interpolation.

var score = 98
print("I got \(score) marks in my exams")
// Prints: I got 98 marks in my exams

Compound Assignment Operators:

Swift has shorthand operators that combine one operator with an assignment, so you can change a variable in place. Above all, compound assignment operators are a convenient way to update a variable’s value:

  • += add and assign the sum
  • -= subtract and assign the difference
  • *= multiply and assign the product
  • /= divide and assign the quotient
  • %= divide and assign the remainder
var numberOfMangoes = 11
numberOfMangoes += 1
print("There are \(numberOfMangoes) mangoes.")

//Prints: There are 12 mangoes.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: