Constants And Variables In Swift

Constant and Variables in swift are pretty much inspired by Javascript. If you had got a chance to work on ES6 javascript recently, you will find these detail related to Swift.

For Variables:

int    i, j, k;

char   c, ch;

float  f, salary;

double d;
For Constant:
const int  LENGTH = 10;
var helloText = "Hello, SwitchToSwift”

The declaration uses the keyword var which stands for variable. After that, we give the variable a name hello text. Then you have the equal sign, known as the assignment operator = and then you have a string that needs to be enclosed in double quotation marks.

Declaring a constant uses the let keyword. In this case, we are going to define a constant g;

let g = 9.8

Constant values cannot be changed after they are declared.

so if ,we try to change the value of our constant π we’d get an error message:

let g = 9.8

g =9.2

//error: cannot assign to ‘let’ value ‘g’  g = 9.8

You can even declare multiple variables on the same line by using a comma separator.

var x = 5, y = 6, z = 7

Now what if we don’t want x to store number values, we want it to store a String type. This is when we use what’s called explicit type declarations.

var x : String 

Now if we try to put a number to this variable we gonna get an error because we gave type as String

x = 5

// error: type ‘String’ does not conform to protocol IntegerLiteralConvertible’


Leave a Reply

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