iosswiftcs193pitunesu

CS193P Assignment 1 π


I'm studying CS193P course on iTunesU. I have a question related to the 1st assignment - Programmable Calculator. I've attempted to add the π button as described in the lectures and the homework assignment. However, pressing the π key followed by enter or and operand causes a crash with the message: "fatal error: unexpectedly found nil while unwrapping an Optional value"

class CalculatorBrain
{
private enum Op {
    case Operand(Double)
    case NullaryOperation(String, () -> Double)
    case UnaryOperation(String, Double -> Double)
    case BinaryOperation(String, (Double,Double) -> Double)

    var description: String{
        get {
            switch self {
            case .Operand(let operand): return "\(operand)"
            case .NullaryOperation(let symbol, _): return symbol
            case .UnaryOperation(let symbol, _): return symbol
            case .BinaryOperation(let symbol,_):return symbol
            }
        }
    }
}

private var opStack = [Op]()

private var knownOps = [String:Op]() //initialize dictionary

init() {
    func learnOp (op: Op) {
        knownOps[op.description] = op
    }
    learnOp(Op.BinaryOperation("×", *))
    learnOp(Op.BinaryOperation("÷", { $1 / $0 }))
    learnOp(Op.BinaryOperation("+", +))
    learnOp(Op.BinaryOperation("−", { $1 - $0 }))
    learnOp(Op.UnaryOperation("√", sqrt))
    learnOp(Op.UnaryOperation("sin", sin))
    learnOp(Op.UnaryOperation("cos", cos))
    learnOp(Op.NullaryOperation("π", { M_PI }))
}

I've been able to force it in the view controller, but know this is a hack:

var displayValue: Double{
    get{
        // I don't understand why I had to put this hack in for π
      //  if (calcDisplay.text != "π"){
            return NSNumberFormatter().numberFromString(calcDisplay.text!)!.doubleValue
       // } else {
       // return M_PI
       // }
    }
    set{
        calcDisplay.text = "\(newValue)"
        userIsInTheMiddleOfTyping = false
    }
}

I'm new to Swift / Obj-C. Can someone please help point me in the right direction to resolve this?

Full source: https://github.com/philnewman/Calculator


Solution

  • NSNumberFormatter().numberFromString is designed to convert numerical strings into numbers. A "numerical string" is a string whose contents are of the form:

    ([:digit:]+(\.[:digit:]*)?)|(\.[:digit:]+)
    

    Where [:digit:] is the set of digits {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}.

    Essentially, it will only parse numbers from strings whose characters are within 0-9 and an optional ..

    Because π doesn't belong to this set of 10 characters, it is rejected and the NSNumberFormatter is unable to parse a number from the string.