We now know how to perform a basic calculation, but we could do that on a simple calculator. To take advantage of programming, we must learn how to use variables!
Variables in Swift
A variable is simply a named value stored in memory. It's a way of labeling (naming) some data (piece of information, value). Then, using the name, we can refer to that data for reuse or modification.
The initial creation of a variable is called a declaration. To declare a variable in Swift, use the keyword
var. Let's use our salary example from previous chapter, it refers to the first year earnings of $50K:
var annualRevenue = 50
This line means: "create a variable called annualRevenue and set its value to 50(K)."
You can think of computer's memory as a giant dresser that has a humongous number of drawers. In the example above, we are designating a drawer for the number $50K and we are sticking the label "annualRevenue" on it.
Now, let's calculate the average annual profit for 2 years assuming the revenue increases to $60K in the second year and expenses are $30K and $35K respectively.
For example, let's create a program that calculates the average age difference that I have with my parents. We did it in the exercise of the previous chapter like this:
(50 - 30 + 60 - 35) / 2.0 // $22.5/year
The calculation works, but we haven't taken advantage of programming using variables. Let's correct that and store the profit for each year in a separate variable:
var firstYearProfit = 50 - 30 // $20K var secondYearProfit = 60 - 35 // $25K
firstYearProfitholds the value 20
secondYearValueProfitholds the value 25
Now, to calculate the average, it is sufficient to add these two variables and divide the sum by 2:
var averageAnnualProfit = (firstYearProfit + secondYearProfit) / 2
This is a more comprehensive way to perform our calculation, isn't it?
How to create names?
Here are general recommendations for creating names:
Use descriptive names throughout your code. It may get a bit lengthy, however it will benefit you and your team in the long run by providing for easier readability and code maintenance.
Spell it out! Avoid abbreviation or shortening words when possible, even if a shorter version appears obvious. For example
annualRevenueis better than
Follow a common naming convention. One of the popular naming conventions is called Camel case (also known as Camel caps) - a compound phrase that consists of multiple words without spaces or punctuation. The first word is written in lowercase and all other words are capitalized. For example
myExcellentEarnings(Wiki tells more)
Let's calculate Jenny's savings
We'll start by storing the initial information in variables, in particular, the price for the coffee station and the daily allowance Jenny can put aside:
var price = 1499 var dailyAllowance = 10
dailyAllowance contain the initial information we received from Jenny. We are able to use it to calculate the time that Jenny need to save for the purchase:
var savingDays = price / dailyAllowance
The term variable implies something that varies - changes it's value. Looking back at our code we can observe that once we assign a value to our variables, we never change them - they stay constant. This is a handy example as it happens in programming very frequently. For a number of reasons, there's a special case for variables in Swift to accommodate such situation. The are called constants.
Constants in Swift
Constant is a variation of a variable in a traditional sense, that cannot be modified. To declare a constant in Swift, use a keyword
let. For example:
let constant = 2 // cannot be modified
This variable cannot be changed. So, let's experiment with the following example:
var annualRevenue = 50 annualRevenue = 60
In the code I declared a variable
annualRevenue and set its value to 50. Then I changed its value to 60. Our variable
annualRevenue now holds value 60 and our code executes smoothly :zorro:!
Now, let's change the declaration from variable to constant:
let annualRevenue = 50 annualRevenue = 60
Playground immediately presents an error:
And offers you a solution:
So, why would we use constants if they are the same as variables but with a limitation?
As a general rule, if a variable never needs to be modified, use constants instead of variables. Let's follow the rule and modify our code:
let price = 1499 let dailyAllowance = 10 let savingDays = price / dailyAllowance
As we noticed previously, none of our variables need to be modified, so we declare them as constants instead by using a keyword
Our code is improving every instant. To make further progress, let's take advantage of comments!
Comments play a very important role in programming. They help you and your team to better understand the intent behind the lines of code.
Why do I need help understanding what I, myself, wrote in the code o_O?
Believe it or not, even if you, yourself, wrote that code, there will be a time (perhaps in the near future) when you, yourself, will wonder: "Why on Earth is this the way it is?". Often times, there's an immediate solution that pops in your head that appears to be better than the one implemented in the code. Likely, you had already thought of that 'immediate' solution at the time of writing and decided against it. Good thing you put that in a comment :zorro:!
There are 2 types of comments:
Single line. A single line comment is marked by using double forward slash
//. Everything that appears after until a new line will be treated as a comment and will be ignored by the computer when executing the code.
// initial data let myConstant = 1 print (myConstant)
Multi line. Multi line comment is marked by using opening and closing forward slashes followed/led by an asterisk
/* your comment */. All the content between the opening and closing markers will be treated as a comment, whether it's single-line or multi-line. For example:
/* initial data */ let myConstant = 1 /* let's print it out to make sure the value is correct */ print (myConstant)
Considering your new knowledge, let's apply it right away and improve our code:
/* initial data */ // price of the purchase let price = 1499 // daily savings allowance let dailyAllowance = 10 /* calculations */ // days to save let savingDays = price / dailyAllowance
Great job with making so much progress! We've cleaned up our code and will be able to continue building our solution using our new knowledge and techniques!
To declare variables, we use keywords
let. Variables declared with
varcan be modified, variables declared with
letare constants and cannot be modified.
To comment code, we use:
//to mark single-line comments
/* */to mark multi-line comments.