Data storage is a technique using which we store data in computer's memory and we name that memory location for our convenience. Whenever we store any data it is stored in memory at any address as provided by the operating system and this memory location is marked by a name which we give in our software code. This naming of memory address helps us to work smoothly without going deeper into the hardware and operating system mechanism of memory management and we feel like solving an algebra sum. like x=3; y=4; sum=x+y;
Sometime we want to store some data which is fixed throughout the execution of the block of code where it is defined. These kind of data is needed to be protected from being wrongly/unintentionally modified. So this purpose swift has provided Constant or Immutable Data Storage. With let keyword we can make data safer from being changed.
Once any data is made constant or immutable it won't allow you further to change the value. So lets try to change it and see what happens.maximumSpeedOfCar = 200
If you try this code, it will give you an error and won't allow you to do so. On output console you would notice something like this.
It's similar to const keyword in c or final in java.
Most of the time in our program we want to do or we do many calculations and keep storing the result to a given storage name means we are changing the values of data stored at a specific memory address. Swift has provided variable data storage for this purpose. We need to use the keyword var as given in below line.var currentSpeedOfCar = 40
Unlike immutable data storage, this will not stop you to make any change. So you can change values of this type anytime and anywhere in your code you need to do so.
Note: Both constants and variables need to be defined before it could be used and there must be a valid value to define them.
Sometime we want to store some data but it is not present or known at that time so we create a placeholder to store some data latter. We store the data when it's available like after a calculation is done or data is read from input or file or network. These are optional data storage. For example everyone is expected to have a mobile phone number but there could be some cases where it could not be present for someone.var mobileNumer: Int ?
In this variable the value would automatically assigned as nil
Try below two lines of code in playground and see what happens.var mobileNumber: Int? print (mobileNumber )
Output on console: nil
Now try below written piece of code:var mobileNumber: Int?
Output on console:Optional(92832878)
See the output carefully and try to observe. First line has printed value inside Optional() while next line has printed normally. If you see carefully there is an exclamation mark added with mobileNumber as mobileNumber! which does the magic and removes the optional() from getting printed.
I will discuss this in detail latter in topic Optional Binding