Encapsulating variables

if statements introduce a new concept scope, which is a way to encapsulate variables through the use of braces.

Let’s take an example. Imagine you want to calculate the fee to charge your client. Here’s the deal you’ve made:

You earn $25 for every hour up to 40 hours, and $50 for every hour thereafter.

Using Swift, you can calculate your fee in this way:

var hoursWorked = 45

var price = 0

if hoursWorked > 40 {

let hoursOver40 = hoursWorked - 40 price += hoursOver40 * 50 hoursWorked -= hoursOver40

}

price += hoursWorked * 25

print(price)

This code takes the number of hours and checks if it’s over 40. If so, the code calculates the number of hours over 40 and multiplies that by $50, then adds the result to the price. The code then subtracts the number of hours over 40 from the hours worked. It multiplies the remaining hours worked by $25 and adds that to the total price.

In the example above, the result is as follows:

1250

The interesting thing here is the code inside the if statement. There is a

declaration of a new constant, hoursOver40, to store the number of hours over 40. Clearly, you can use it inside the if statement. But what happens if you try to use it at the end of the above code?

...

print(price) print(hoursOver40)

This would result in the following error:

Use of unresolved identifier 'hoursOver40'

This error informs you that you’re only allowed to use the hoursOver40 constant within the scope in which it was created. In this case, the if statement introduced a new scope, so when that scope is finished, you can no longer use the constant.

However, each scope can use variables and constants from its parent scope. In the example above, the scope inside of the if statement uses the price and hoursWorked variables, which you created in the parent scope.

results matching ""

    No results matching ""