cs193p – Assignment #1 Extra Task #4

Please note, this blog entry is from a previous course. You might want to check out the current one.

Make one of your operation buttons be “generate a random number between 0 and 1”. This operation button is not a constant (since it changes each time you invoke it). Nor is it a unary operation (since it does not operate on anything).

In the interface builder change the name of a button to “rand”:

Storyboard calculator adding random function
Storyboard calculator adding random function

Add an operation without operands to the the calculator model:
[swift]
private enum Operation {

case NullaryOperation(() -> Double, String)

}
[/swift]

The “random” operation returns the function generating the random number as well as a string for its description:
[swift]
private var operations: Dictionary<String,Operation> = [

"rand" : Operation.NullaryOperation(drand48, "rand()")
]
[/swift]

… which are used to calculate the result and the description:
[swift]
func performOperation(symbol: String) {

case .NullaryOperation(let function, let descriptionValue):
accumulator = function()
descriptionAccumulator = descriptionValue

}
[/swift]

The complete code for the extra task #4 is available on GitHub.

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

2 thoughts on “cs193p – Assignment #1 Extra Task #4”

  1. Hi Martin,

    Thanks a lot for putting these answers together! I was really stuck on the last part of assignment #1.

    Will you be adding any more assignment answers for 2016?

    Thanks!

    Blake

Leave a Reply

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