cs193p – Assignment #2 Task #3

Add the capability to your CalculatorBrain to allow the input of variables. Do so by
implementing the following API in your CalculatorBrain …
[swift]func setOperand(variable named: String)[/swift]
This must do exactly what you would imagine it would: it inputs a “variable” as the operand (e.g. setOperand(variable: “x”) would input a variable named x). Setting the operand to x and then performing the operation cos would mean cos(x) is in your CalculatorBrain.

As you might have seen form the previous tasks – the tasks of this assignment are not that easily separable. Let’s start by adding two new types to operation structure. One for operands and one for variables:
[swift]
private enum Operation {

case operand(Double)
case variable(String)
}
[/swift]

And create a stack of those operation to do something with later on:
[swift]
private var stack = [Operation]()
[/swift]

Finally add the new api method which just puts the variable on the stack:
[swift]
mutating func setOperand(variable named: String) {
stack.append(Operation.variable(named))
}
[/swift]

The change of the structure breaks the switch statement. So for now, a quick fix:
[swift]
mutating func performOperation(_ symbol: String) {

default: break // nothing to do for operands and variables
}
}
[/swift]

The complete code for the assignment #2 task #3 is available on GitHub.

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published. Required fields are marked *