我正在 iTunesU 上学习 CS193P 课程。我有一个与第一个作业有关的问题 - 可编程计算器。我尝试按照讲座和家庭作业中的说明添加 π 按钮。但是,按 π 键后跟 enter or 和操作数会导致崩溃并显示以下消息:“致命错误:在展开可选值时意外发现 nil”
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 }))
}
我已经能够在视图控制器中强制它,但知道这是一个 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
}
}
我是 Swift / Obj-C 的新手。有人可以帮我指出正确的方向来解决这个问题吗?