Taking the Tax Calculator Further


In the last tutorial, we created a tax calculator app. If you didn’t follow along, I encourage you to read it first as this tutorial builds off the last one.  Today, we’re going to take the existing tax calculator all a but further by adding a tip calculator. This will again be rather straightforward and simple, but offers a easy introduction into swift.

I. Plan

Ok, so what do we want to accomplish here? Well, we want to find the amount based on a tip of let’s say 12% and then add that tip to the tax total to create a grand total for the bill.  To do this,we’re going to need some more variables – a tipPercent variable to hold the tip amount (12%), a tip variable to do some calculations, and a grandTotal variable to find the total.

II Coding

Let’s dive in!  First, we need to create a new variable called tipPercent to hold the 12%.  Let’s create a float of 0.12.

var tipPercent = 0.12

Next, inside the calculation  function, create a new variable called tip which will calculate the tip of 12% based on the total we found in the previous tutorial.  TO do so, multiply tipPercent (the variable which holds 12%) by the total to find the amount.

var tip = tipPercent * total

Notice that the tip is $3.15. Next, we need to find the grandTotal by adding the tip we calculated above to the total amount we calculated in the previous tutorial. Create a new variable and call it grandTotal.

var grandTotal = tip + total

Bam! Our total is $29.40! Next time I’m at a resturant, I’ll just write this program and find the answer!

But wait, we should have the program print out a nice little result in a string, right? Let’ do that now.

Create a constant called printed  and use string interpolation to print our the values.  Make the value a string with the variables inside.  Here’s how you do it.

let = "The tax was $ \(tax). The total cost $ \(total) and the tip was \(tip).  Ultimately, it cost me $ \(grandTotal)."

When you use a variable or constant inside a string with the \(name_of_variable), it’s called string interpolation.

Update:Download the full source code here.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s