Building A Calculator In Swift 4

Malcolm Kumwenda
2 min readSep 20, 2017

Using NSExpression to build a calculator.

The Swift language never seizes to amaze me with all the functionality it provides. I gave myself the task of building a simple calculator as a coding-kata. I had already built a calculator in Java and I remembered the horrendous number of ‘if’ and ‘case’ statement that does all the mathematical logic. So I started out and built my layout as seen in the screen above. I used Snapkit to layout the views. This post won’t cover Snapkit but you can read this as an introduction to Snapkit.

The ‘Math’

So we are going to perform all calculation with no ‘if’ or ‘case’ statements. You might be wondering how will be do that ? I mean how will Swift know when to add or subtract or perform any other mathematical function ? Welcome your friend when doing maths in Swift, NSExpression ! Who and what is NSExpression ?

An expression for use in a comparison predicate.

Comparison operations in an NSPredicate are based on two expressions, as represented by instances of the NSExpression class. Expressions are created for constant values, key paths, and so on.

That’s the definition from the Swift documentation. Does not tell us much. It is will be easier to see NSExpression in action to better understand it’s power.

let mathExpression = NSExpression(format: "16 + 30")
let mathValue = mathExpression.expressionValueWithObject(nil, context: nil) as? Int

Yes that is all the code you need to do the math 😱👏🏾🎉. NSExpression is able to evaluate way more than simple mathematical equations. This post right here goes into way more depth with NSExpression and the functionality it can give you.

How To ‘Math’

So in the one function above I was able to perform all the necessary mathematical calculations for my calculator.

Just like that thanks to NSExpression I had built a fully functional calculator. The final calculator has a number of more features such as a history of the users operations with the ability to go back to a previous operation. You can have a look at the full implementation on my Github page.

--

--