var DoMath = “and stuff”
Building a calculator in swift can seem a little daunting. However, like many things, if you break it down it becomes fairly simple. We wont build a full on app. Just do some basic logic to help you get started. I hate long winded intro’s so wer’e going to jump straight in.
Let’s start by opening a playground in xcode. Name it something you can remember so you can reference it later on.
So let’s think about what we need as far as calculations go.
We need to:
- Hold the numbers and results
- Calculate Equations
Pretty simple right!?
So what is the logic behind all this? Well let’s go to our playground. As far as logic goes we will need to use a function, an If statement (alternatively a guard let), and a switch statement. If you don’t know what a function, if statement, or switch is, or you need a refresher, I have included links to documentation.
To add the numbers and results we will use the following:
Next lets add the operator and equal buttons:
Pretty simple so far! Let’s keep it that way! Now lets create a function.
This is where the switch statement shines. We will switch through our operand to do the correct calculations.
We are not done with our calculatorBrain yet! Lets add an initializer after calculatorBrain so we can get our numbers and operators. We will also store that input into the variables we created earlier. When you are done it will look like this:
Now if we call calculatorBrain we will see the correct answer in the output:
Thats it! Simple Logic for a basic calculator. There is more that goes into actually creating a calculator app. In addition to this you will also have to clear the calculator, add a decimal, add buttons and convert that input. However, understanding the fundamentals behind why things do what they do is essential for expansion.
Did this help you? Let me know below in the comments.