Making a Tax Calculator App

cropped-swift2.png

Note: This is a beginner tutorial. 

Hey there.  Today, we’re going to make a simple little tax calculator app in Xcode 6’s playground.  This will be a very simple tip calculator, but nonetheless, it will expose you more swift code. If you’ve been following along with a few of our other articles, you should feel comfortable with what’s going on in this tutorial.

Part I

Before we get started, I think it’s best if we maps out what we’re going to do.  So let’s take a look…

We need several variables – one to  store the cost of the bill, one to store the tax amount, one to store the amount when multiplied by the tax, and one to store the total.  If that’s a little confusing right now, keep in there and it will make sense by the very end!

Part II – Coding!

Now that we have a basic plan of what we’re going to be doing, let’s dive right in and take a look.

Make sure you’re using Xcode 6 (if you’re not sure, take a look at our earlier tutorials).  Create a new playground and name it taxCalculator.  Now, delete the pre-made string value Xcode made but keep the import Cocoa line.

Great!  Now, let’s add the amount variable. To declare a variable, use the var keyword.  Let;s call this variable amount and set it to a float value of 25.00.

var amount = 25.00

Next, we need to declare the taxPercent rate and let’s set that to 5%. To do so in code, let’s create a new variable called tax and set it to a value of 0.05. Again, this value is a float, but we don’t need to explicitly declare it as a float because swift can detect it as one.

var taxPercent = 0.05

Great! We’re established two variables. Now, it’s time to use those two variables. Let’s create a function using the func keyword and call it calculation.

func calculation(){
}

You now have an empty function. Next, let’s set some variables in the function.  Declare a new variable called tax and set it equal to the amount variable times the taxPercent variable.  This will generate the amount of the tax.

func calculation(){
var tax = amount * taxPercent
}

Next, set another variable and call it total. Set it to the tax variable times the amount variable. Your function should look like this so far.

func calculation(){
   var tax = amount * taxPercent
   var total = tax + amount
}

Now, just call the calculation function.

   calculation()

Awesome! You now have a working tax calculator. We’ll continue to fine tune this in future tutorials, but it’s really easy to do this in swift, isn’t it?

Update: You can download the entire source code here

Advertisement

One thought on “Making a Tax Calculator App

  1. Pingback: Taking the Tax Calculator Further | Swift Language

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 )

Facebook photo

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

Connecting to %s