Variables in Swift

The first thing we do in any programming language is create variables. So lets get started. In Swift we do this by using a keyword “var“.  The variable name is generally camelCased using lowercase first letter, e.g areaOfCircle; preimeterOfSquare; surfaceArea etc.

The first question you will have is do we need to mention its type before we assign a value to it? Can it hold decimal;non-decimal;strings;boolean;etc? If are asking these questions then you have prior programming knowledge.

Lets address these questions.

  1. In Swift we do not need to specify the data types explicitly. Swift does something called “Type Inference” and assign the type to the variable name implicitly.
  2. Type inferencing infers the data type of the variable depending on the value assigned to it by using the ‘=’ operator.
  3. Thus areaOfCircle is inferred as a floating point (decimal) variable and radiusOfCircle is inferred as integer variable.

In swift we cannot change the data type of the variable once it is assigned to it implicitly. If we try to assign the value ‘true’ to either of the above mentioned variables;we will get a compile time error. This is coz the data type was inferred as digits (floating point and int) and not logical (boolean).

It is not mandatory to assign a value to the variable  after its declared. You can declare the value and latter. But you need to specify the type of the variable. This is called as ‘Type annotation‘. It is done by using “:” after the variable name.

Here the variable radiusOf Circle is declared to hold only Integer (non-decimal) values.

Data types:

The variables can have the following data types as ‘type annotation’.

  1. Int (real no)
  2. Float (decimal no)
  3. Double (decimal no of huge range)
  4. Bool (true/false)
  5. String (sentences)
  6. Character (single alphabet/symbols)
Type Annotation and Type Inferencing:

In swift we can declare the variable and assign it some value as follows

Next we will understand how to declare constants in Swift.