ios - 如何让我的计算器快速添加句点?

标签 ios swift cs193p

这是我的 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/

相关文章:

ios - 向 UITable 添加 subview

ios - 在具有 JSON 来源的 NSDictionary 上应用过滤器并计算平均值

swift - 你如何在 Swift 3 中编写完成处理程序?

ios - Swift 导入在包含框架时出现错误 "Could not build objective-C module ' Twitter'"

ios - 从 cs193p 下载的 Photomania 应用程序显示一个空的 TableView

ios - 上传前在 XCode 中构建应用程序时测试架构是否正确

ios - Xcode 10 Arabic (RTL) Storyboard无法加载

cocoa-touch - UIWebView:当 "touch up"在链接之外时取消打开链接?

ios - 无法设置 RightBarButtonItems 的位置

swift - CS193P Smashtag 流行度额外任务 #3 - 使用 "IN"关键字仅获取新推文