Saturday, April 7, 2018

Swift Variables, Constants

Variables: In swift, a variable holds some data, now its data could be a value, it could be a reference to an object or it can even point to a function.

Variable has a couple of distinct parts, let's break it down, them here



var str = "Hello, playground"

Variable need to be declared before they can be used, so this 'var' keyword is used to declare a new variable, following the var keyword you have the variable name 'str' that's it.

Now taking look at the whole line, what we have on the right-hand side there, that's some data,  we didn't say that variable hold some data, Here = sign in between variable name and piece of data that mean assignment operator.  That means assigning that str with data.



In above line, the playground shows the error because the data is not matching.
Let's start learning about the data types.

Before starting data types, let's discuss briefly naming conventions, naming variable we usually follow the camelcase.


Constants: Like the variable except it can't be reassigned new data after the first assignment.
Uses the 'let' keyword instead




Why would I or everyone use constants, if it more limited it's in functionality, instead if I declare everything in the variable I have all the flexibility I want.

Well, there are a couple of reasons why you would want to use constants, when making sense, for one thing, it helps computer works little more efficiently because it knows exactly what that constant will be and that not going to change.

Next chapter Data Types

0 comments:

Post a Comment