Swift Basic Data Types and Variables

On any programming language, you would be using tons of different kinds of data types, data types is the kind of the data, in Swift it’s kind can be a string, character, integer (Int), boolean (Bool) etc. and then you may need a place in memory to store this program data. The place to store this data is called a variable.

Basic Data Types

The most basic data types are the following:

  • Int for integers
  • Double and Float
  • Bool for boolean values
  • String and Character for textual data

Variable Declaration

Simply you declare a variable starting with the reserved keyword “var” identified by a name then assign it a value using an assignment operator “=”, the value can be of any data type

var str = "Hello World"

On this example we declared a variable called “str” and assigned it a “String” type with a value of “Hello World”.

If we want to change the value, no need to start with var, you can directly assign it a new value.

str = "Goodbye"

We can declare Integers, Doubles and multiple variable declaration of different types separated by a comma

// Integer declaration
var age = 45

// Double
var x = 0.0
var y = 1.0

// multiple variables
var car = "Tesla", var hasPhone = true, var z = 1.0

Swift is smart that it inferred the data type when a value was assigned to it. Basically meaning we didn’t need to specify that data type is a string or an integer or boolean, just by the value Swift can say “Hey, this value is a string and I’ll store it as a string“.

While rare you can create a variable and provide the data type annotation if needed.

var red, green, blue : Double

On example above the multiple variables were declared of having a type of Double.

One thought on “Swift Basic Data Types and Variables

Leave a Reply

Your email address will not be published. Required fields are marked *