Swift Constants, Variables, and Data Types

Swift Constants, Variables, and Data Types

In this lesson, you'll learn how constant, variables, and different data types in Swift.

Variables

Variables may change during the lifetime of the app. you can define variables using the var keyword

var age = 40
print(age)

The code above would print 40  to the console.

Let's try to assign a new value.

var age = 40
age = 50
print(age)


The code above compiles without errors.  This would print 50 to the console.

Constants

When you need a value that won't change during the lifetime of the app. you will need to use a constant. you can define constant using the let keyword.

let name = "Tim Apple"

Let's try to assign a new value.

As you can see from the screenshot above you cannot change the value of the constant.

Data Types

Every constant or variable in Swift has a  data type specifying its kind of value.

For example

var age: Int

In the above, Int is a data type that specifies that the age variable can only store integer data.

Here are the most common types in Swift.

Name Type Example
Integer Int 10
Float Float 3.14
Double Double 3.14159265358979
Boolean Bool false
String String "Swift is awesome"
Character Character "N"

If you liked this tutorial, please subscribe and share this with your community. Cheers!