Swift - Constants & Variables

Lets talk about Constants and Variables in Swift.

Constants:

As name implies a meaning in programming world, a constant value cannot be changed after assignment. In Swift, a constant can be created using keyword 'let'. Lets create our first constant in Swift and assign a value.

let letNumber = 10.0


Changing the value of this above constant will throw an error.


letNumber = letNumber + 10    //  Cannot assign to ‘let’ value ‘letNumber’


Variables:
A variable is a property that are liable to changes. A variable value can be changed after initialisation or during run time. To create a varaible in Swift, use 'var' keyword.

var varNumber = 20.0

You can change the value of a variable and it will work.

varNumber = varNumber + 10    //  see. it works.

In both examples, we didn't mention the data type of 'letNumber' and 'varNumber' properties. This is because Swift automatically infers the data type of the property based on the value assigned to it. Since we assigned double value, it can also be written like this,

var varNumber: Double = 20.0

Syntax time

To create a property in Swift, we can use 'let' or 'var' keywords based on our requirements. The syntax to create a property is,


keyword  variable_name : data_type  = value


keyword - let, var

variable_name - the property name that is referred to store the value
data_type - the property data type
value - value assigned during initialisation



Same concept applies for Strings too.


let letString = “This is like NSString”

var varString = “This is like NSMutableString"

To summarise the difference between Constant and variable, Constant properties are immutable and variable properties are mutable. Considering the above two strings, you can say 'letString' property resembles NSString and 'varString' property resembles NSMutableString objects in Objective C.

A constant or variable name supports valid unicode characters.

Don't's:
  • Avoid using maths symbols, arrows invalid unicode points , line and box-drawing chars while creating a variable or constants. 
  • Don’t start naming a constant or variable with numbers. It can contain in-between but not on start.


One More Thing:
You might remember the fact that semi-colons (;) are not required at the end of each statement in swift.

Comments

Popular posts from this blog

Swift - Strings

What's new in Swift 4!

Swift - Classes