Swift language: Constant and Variables

Introduction to SWIFT language

As all developers related to IOS and mac OS X app development are aware of the fact that Apple launched new programming language to develop IOS and mac OS X apps. This new programming language is named as SWIFT. In this post we will cover basic part of the language.

Constants and Variables:

As the terms are self explanatory, constant refer to the values which never changed during the life of algorithm or during runtime, whereas variables refers to the values which can be changed during runtime or life of our program. The value of constant cannot be changed once set whereas variable are totally opposite to constant.

Declaring constant and variable:


Declaration of constant and variables

Thumb rule of programming is that you have to declare variables/objects before using them in your program. In SWIFT you can declare constant using let keyword and variable using var keyword. Let us take an example, we will create a constant for maximum number of lives player had in a game and  a variable to keep track of live used by the player in a game.

  • let maximumNumberofLives = 5;
  • var currentLive = 0;
In above code we declared our constant as integer value, as we specify an int to our constant, same is for variable. You can give different data type values to them. For example giving float value 
  • let maximumNumberofLives = 5.0;
  • var currentLive = 0.0;
You can declare multiple constants or multiple variable in a single line, separated by comma
  • var x = 0,y = 0,z = 0;
  • let x = 0,y = 0,z = 0;
You can provide data type to variable and constants so that you can store or provide values later, commonly known as typeAnnotations. For this use syntax
Keyword name of Constant: datatype  
  • var message: String
Above example creates a variable with datatype string, colon can be read as “…of Type..”, so you can read above line of code as
Declare a variable called message of type string. Now you can give any value to the message variable as
  • welcomeMessage = "Welcome to Swift Language";
To print message on console you can use println() function
  • println("This is a string");

To pass values in println() you can pass the value i.e your variable or constant inside a parenthesis and placing backslash in front of opening parenthesis.

  • println("The current value of friendlyWelcome is (welcomeMessage)");

Though its not compulsory in SWIFT language to terminate each line of code with semicolon, its totally your wish whether to use it or not.