Mis à jour le 29/08/2024

Utilize conditions

Jenny's infinitely thankful for your help and she's impressed by your progress. It has inspired you to come up with new ideas and improve her strategy.

Now Jenny has realized that she can add a few more dollars to her savings  on certain days. In fact, she can double the amount of daily savings on the first day and triple it on 10th and 20th. She, however, has decided to not risk buying too many pastries without first making sure her customers will like them. So she has decided not to invest the additional contributions into this new pastry adventure just yet. She would like to see how those extra savings will affect the final result.

Here we go again, some more information to improve our program further!

The primary focus of this chapter is - conditions!

Let's take our code:

``````// initial data
var money = 0.0
let trialPeriod = 30
let dailyInvestment = 10.0
let pastryCost = 2.50
let pastryPrice = 5.50
let numberOfPastries = dailyInvestment / pastryCost

for _ in 1...trialPeriod {
// Jenny tops up savings money from her daily profit
money += dailyInvestment
// Jenny spends daily allowance to purchase as many pasteries as she can
money -= pastryCost * numberOfPastries
// Jenny sells new pastries to her clients
money += numberOfPastries * pastryPrice
}

print("\$\(money)") // \$660.0
``````

We need to add extra savings into our calculations. Unlike previous contributions, the new once will not happen every day, so we cannot simply adjust the code that will be executed at every iteration. What we need instead is this:

• 1st day - add an extra \$10 to the total savings amount (double the daily amount)

• 10th and 20th day - add an extra \$20 (triple the daily amount)

Programmatically, it would look something like this:

``````if it's the 1st day:
add dailyInvestment * 2 to money // double regular amount
if it's the 10th day or the 20th day:
dailyInvestment * 3 to money // triple regular amount
otherwise:
add dailyInvestment to money // regular amount
``````

In this world, everything is possible - including this. We just need to learn a couple more things starting with a new data type!

Here we're going to add yet another data type to your programming arsenal.

• Int

• Float

• Double

• String

• Range

• What's Next?

Next comes  `Boolean`! A variable of boolean type can hold only two values:  `true`   or  `false` . Boolean is the simplest data type.

For example :

``````var theCourseIsExcellent = true
var theAuthorIsHumble = false
``````

Makes sense, doesn't it?

To declare a boolean variable we specify its type as   `Bool` :

``````var iAmABoolean: Bool
``````

What happens if a variable is used before it's been initialized?

A compilation error happens! Ha! That's the safety net in Swift - you cannot run your code until you correct such occurrence !

We are back to learning operators! Some operators are only applicable to certain data types. We already know basic numeric operators:  `+ - * /`  that are applicable to numeric data types:  `Int` ,  `Double`  and`Float`. And `+`  operator is used for  `String`   concatenation. And here are some new ones that are specific to   `Bool`:

Comparison operators

As the name suggests, those operators are used to compare two values. There are 6 of those:

• `==`   Equal to (exactly the same)

• `!=`   Not equal to (different in any way)

•  `<` Less than

•  `<=` Less than or equal to

•  `>` Greater than

•  `>=` Greater than or equal to

Here are some examples using numeric comparison:

``````2 == 2 // true
2 == 3 // false

4 != 4 // false
4 != 5 // true

1 < 2 // true
1 < 1 // false

1 <= 1 // true

3 > 4 // false
5 > 4 // true

5 >= 4 // true
``````

Logical operators

These operators allow us to combine boolean values: either specific boolean values or results of expressions. There are 3:

• `&&`   - logical AND: the result is true only when ALL the participating parts are true. Ex.: the result of `expression1 && expression2`  will be true only if expression1 is trueAND expression2 is also true.

• `||`   - logical OR: the result is true when at least ONE of the participating parts is true. Ex.: the result of  `expression1 || expression2`   will be true if expression1 is trueORexpression2 is true. It will also be true if both expressions are true

• `!`   - logical NOT: it simply inverts the given expression: the result of  `!expression1`  is true when expression1 is false; the result is false when expression1 is true.

Here are some examples:

``````true && true // true
true && false // false
false && false // false

true || false // true
true || true // true
false || false // false

!true // false
!false // true
``````

Same rules apply when more than two expressions are chained together:

``````true && true && true // true
true && true && false // false

true || false || false// true
false || false || false// false
``````

Like with numeric operators, the logical operators respect the priority of operations - the inversion operator (  `!`  ) comes first, then AND operator (  `&&`  )  and, finally, OR operator (  `||`  ). For example:

``````false || true && true // false
!false && true || false // true
``````

As with numeric operators, use parentheses   `()`   to change the order:

``````(true && false) || true // true
!(true && false || !true) // true
``````

To reinforce what you've learned, practice calculating the result of following expressions:

``````!true && false

!(true && false)

4 < 3 || 4 >= 4

(!(1 == 2) || 3 != 3) && 35 > 34
``````

To check if your calculations are correct, simply copy the code above to your playground project. However, do your best to get the results on your own first!

Well, we've learned boolean types and operators, but what's do we need them for?

To answer this question, let's recall our pseudocode we composed in attempt to help Jenny incorporate her new strategy:

``````if it's the 1st day:
add dailyInvestment * 2 to money // double regular amount
if it's the 10th day or the 20th day:
dailyInvestment * 3 to money // tripple regular amount
otherwise:
add dailyInvestment to money // regular amount
``````

In fact, it matches perfectly the  `if`   pattern that looks like this:

``````if logical expression {
// instructions
}
``````

Interpreting this code, we can conclude, if the result of the  `logical expression`  is`true`, the instructions between curly brackets {} will be executed. Otherwise they will be ignored.

For example, let's try this:

``````if true {
print ("I am executed").
}

if false {
print ("I'm ignored")
}
``````

and observe the result in the console:

`I am executed`

The previous example can be optimized further by merging the two  `if`  blocks into one  `if/else`   combo:

``````if true {
print ("I'm executed")
}
else {
print ("I'm ignored")
}
``````

It basically means, if the expression is true - execute the first block of instructions, if not - execute the second block of instructions.

Practice by completing the code for the following criteria: Create two variables, one with your birth year and the other with that of Barack Obama (1961). Compare them and print "I'm younger than Obama!" if you are younger than Obama, or if you are older than Obama, print "I have more experience than the former president of USA!". Get to work!

``````// No cheating, please!

var myYearOfBirth = 1900
var obamaYearOfBirth = 1961

if myYearOfBirth > obamaYearOfBirth {
// My year of birth is later than Obama's, therefore I'm younger
print("I'm younger than Obama!")
}
else {
// My year of birth is before Obama's, therefore I'm more experienced!:)
print("I have more experience than the former president of USA!")
}
``````

Well done!

What if I was born in 1961? I am neither younger nor older!

Indeed! In the example above, the case of years being equal will fall within the else statement. Often times it's necessary to cover more than just 2 scenarios. Using the if/else pattern we can add more conditional criteria within else section. Let's alter our example:

``````var myYearOfBirth = 1900
var obamaYearOfBirth = 1961

if myYearOfBirth > obamaYearOfBirth {
// My year of birth is later than Obama's, therefore I'm younger
print("I'm younger than Obama!")
}
else if myYearOfBirth == obamaYearOfBirth {
// We were borth in the same year
print("I am the same age as Obama !")
}
else {
// My year of birth is before Obama's, therefore I'm more experienced!:)
print("I have more experience than the former president of USA!")
}
``````

You can add any number of  `else if`   statements to handle all the cases you need:

``````var name = "Jenny"

if name == "Jenny" {
print("Hi Jenny, how are you?")
}
else if name == "Joe" {
print("Hey Joe, how's everything?")
}
else if name == "Jessica" {
print("Hello Jessica!")
}
else {
print("I'm afraid we haven't met.")
}
``````

If the name is not any of the specified: Jenny, Joe, Jessica, the instructions in the else block will be executed.

With all this in mind, we are now ready to complete our adjustments for Jenny's savings! It's in your hands now. Transform the code within the loop in order to reflect the new requirement:

``````if it's the 1st day:
add dailyInvestment * 2 to money // double regular amount
if it's the 10th day or the 20th day:
dailyInvestment * 3 to money // tripple regular amount
otherwise:
add dailyInvestment to money // regular amount
``````
``````// No cheating, pelase!

// initial data
var money = 0.0
let trialPeriod = 30
let dailyInvestment = 10.0
let pastryCost = 2.50
let pastryPrice = 5.50
let numberOfPastries = dailyInvestment / pastryCost

for day in 1...trialPeriod {
// Jenny tops up savings money from her daily profit
if day == 1 {
money += dailyInvestment * 2
}
else if day == 10 || day == 20 {
money += dailyInvestment * 3
}
else {
money += dailyInvestment
}
// Jenny spends daily allowance to purchase as many pasteries as she can
money -= pastryCost * numberOfPastries
// Jenny sells new pastries to her clients
money += numberOfPastries * pastryPrice
}

print("\$\(money)") // \$710.0
``````

Not bad at all! Conditions proved helpful in refining our program, we can see how extra savings in specific days when Jenny can afford it, will benefit her saving process!

As our code becomes more sophisticated with every chapter, it's important to provide the best readability and clarity through your personal formatting style and consistency.

There are number of preferable approaches, however it's up to you which one to choose and follow. You will always fall into a group that consists of approximately half of the developer population. It's like dog lovers and cat lovers, there's no right or wrong, just a matter of personal preference.

There is, however, some formatting to be avoided: sloppy inconsistent formatting. Think of your code as a book. Would you appreciate mismatching fonts and sizes, random alignments and nonsense sentences? I bet you wouldn't, even if you were extremely interested in the story!

So, in this chapter we'll figure the styling of curly brackets.

There are variations in style for using spaces in relation to the brackets, as well as for positioning the brackets in relation to the corresponding element line (same or new line). Else/if statements are a good structure to use as examples. Let's look at a few variations.

Using spaces:

``````// no spaces
if expression{
// instuctions
}else{
// instuctions
}

// single space for separation
if expression {
// instuctions
} else {
// instuctions
}
``````

Same line vs. new line:

``````// same line
if expression {
// instuctions
} else {
// instuctions
}

// new line, else on the same line
if expression
{
// instuctions
} else
{
// instuctions
}

// new line
if expression
{
// instuctions
}
else
{
// instuctions
}

// same line, else on a new line
if expression {
// instuctions
}
else {
// instuctions
}
``````

You will have slips here and there and that's ok! No-one is perfect - the important part is intention!

• We've learned a new data type:  `Bool`  for Boolean data, which can hold only 2 values:  `true`  or`false`.

• There are two essential groups of boolean operators:

• Comparison operators:

 == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to
• Logical operators:

 && Logical AND || Logical OR ! Logical NOT
• The `if / else`  statement is utilized to manage different conditional states in a program using the following syntax:

``````if expression1 {
// instructions
} else if expression2 {
// instructions
} else {
// instructions
}
``````
Et si vous obteniez un diplôme OpenClassrooms ?
• Formations jusqu’à 100 % financées
• Date de début flexible
• Projets professionnalisants
• Mentorat individuel
Trouvez la formation et le financement faits pour vous