这是我的 UIButton 的代码
@IBAction private func performOperation(sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.setOperand(displayValue)
userIsInTheMiddleOfTyping = false
}
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
displayValue = brain.result
}
这是我的模型或 View Controller 代码
private var operations: Dictionary<String,Operation> = [
"π": Operation.Constant(M_PI),
"e": Operation.Constant(M_E),
"√": Operation.UnaryOperation(sqrt),
"cos": Operation.UnaryOperation(cos),
"✕": Operation.BinaryOperation({ $0 * $1 }),
"÷": Operation.BinaryOperation({ $0 / $1 }),
"+": Operation.BinaryOperation({ $0 + $1 }),
"−": Operation.BinaryOperation({ $0 - $1 }),
"±": Operation.UnaryOperation({ -$0 }),
"=": Operation.Equals,
".": Operation.Period
]
private enum Operation {
case Constant(Double)
case UnaryOperation((Double) -> Double)
case BinaryOperation((Double, Double) -> Double)
case Equals
case Period
}
func performOperation (symbol: String) {
if let operation = operations[symbol] {
switch operation {
case .Constant(let associatedConstantValue):
accumulator = associatedConstantValue
break
case .UnaryOperation(let associatedFunction):
accumulator = associatedFunction(accumulator)
break
case .BinaryOperation(let associatedFunction):
executePendingBinaryOperation()
pending = PendingBinaryOperationInfo(binaryFunction: associatedFunction, firstOperand: accumulator)
break
case .Equals:
executePendingBinaryOperation()
break
case .Period:
displayTextContainsPeriod()
break
}
}
}
private func displayTextContainsPeriod() -> Bool
{
}
我知道要检查是否存在现有句点 我需要检查字符串是否包含子字符串“.”但我不确定如何在我的 func displayTextContainsPeriod 中获取显示文本
最佳答案
您采用了错误的方法。 .
不应是运算符。你的计算器大脑不应该参与其中。这项工作应该在您的 ViewController
中完成,而不是您的模型。如果 display
尚未包含 .<,它应该像数字一样操作并将
..
字符附加到 display
字符串
您需要考虑输入 .
而用户没有在输入数字的情况。例如,您可能希望以 0.
而不仅仅是 .
开始显示。
关于ios - 如何让我的计算器快速添加句点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466991/