On any programming language, you would need to use various data types like String, Character, Int, Bool etc. and you may need place 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
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. While rare you can create a variable and provide the type annotation.
var red, green, blue : Double
On example above the multiple variables were declared of having a type of Double.