The Graphing Calculator project is a continuation of the previous 2 assignments from the Stanford University CS193P course Developing iOS 8 Apps with Swift, available for free on iTunes. This is the third and final assignment in the Calculator series.
Full source code available here at Github repository
For the other 2 projects, please see:
CalculatorBrain: Assignment 2, Stanford University Winter 2015 (iOS)
Calculator: Assignment 1, Stanford University Winter 2015 (iOS)
This project provides graphing features in addition to the regular calculator functions. Graphs can be plotted by entering expressions where M is the independent variable. Please see examples below.
To plot M, enter:M, Graph
To plot sin(M), enter:M, Sin, Graph
To plot M x cos(M), enter:M, M, cos, x, Graph
Some interesting notes
- The CalculatorBrain is reused to calculate the values of M for graphing
- Plot values are set in the GraphingViewController as the data source of GraphingView
- To fix the sluggish performance when zoomed out and panned, only the number of plots required for the screen width are calculated
- Graph scale and origin is stored in NSUserDefaults
- Upon device rotation, the graph is centered and adjusted slightly with the width and height change ratio
I used existing functionality in calculator brain. Specifically, inside brain, I created a public method that made a calculation based on a program, stored as any object through the property list typecast (we did that in the save/restore part). All the commands were there - I just packaged it in a method. I use this method for a lot of stuff - so I never rewrite code to evaluate a sequence of operands.
In the public interface, that is just a function that is accessible from any instance of brain. In particular, in preparing for segue to the graph view, I pointed the graph view controller to this function. I also passed the program existing in the brain at that moment, so that any expression valid in the calculator can be plotted. The latter was a goal for me because it makes sense. I wanted to avoid rewriting the function that interprets the operands.
The graph view requires a function (can be brain or any other specification) and a "program" that is required in order to plot expressions. So it is a general class requiring a specific form for describing the operations. I take that as a perfectly "legal" solution.
Drawrect then used the function and the program to draw the curves.