gpt4 book ai didi

ios - 如果在数字之前按下计算器应用程序中的运算符(operator)按钮,则应用程序崩溃

转载 作者:行者123 更新时间:2023-11-29 05:37:38 26 4
gpt4 key购买 nike

我是 swift 新手,我设计了一个计算器应用程序,如果我在输入数字之前按下运算符(operator)按钮,应用程序会崩溃并显示给我

error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string " == 1"'



我已将所有数字按钮连接到相同的操作功能
import UIKit

class ViewController: UIViewController {


//outlet of the label
@IBOutlet weak var labelOutlet: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

//action for all the digits and the operator buttons

@IBAction func buttons(_ sender: UIButton) {


labelOutlet.text = labelOutlet.text! + sender.currentTitle!

}

//action for equals to button
@IBAction func tappedEqualsTo(_ sender: UIButton) {

let result = test(labelOutlet.text!)
labelOutlet.text = result

}

//action for clear button

@IBAction func clearbuttonPressed(_ sender: Any) {

labelOutlet.text = ""

}

//action for delete button

@IBAction func deleteButtonPressed(_ sender: UIButton) {

let name: String = labelOutlet.text!
let stringLength = labelOutlet.text?.count
let substringIndex = stringLength! - 1
labelOutlet.text = (name as NSString).substring(to: substringIndex)
}


//function to pass a string and get the value calculated and the again return value is in string format

func test(_ expressrion: String) -> String{
var numinString : String!
if let num = expressrion.calculate() {
numinString = String(num)
print("\(expressrion) = \(num)")
} else {
print("\(expressrion) = nil")

}
return numinString
}

}

为计算输入的字符串而创建的字符串的扩展
extension String {
private func allNumsToDouble() -> String {

let symbolsCharSet = ".,"
let fullCharSet = "0123456789" + symbolsCharSet
var i = 0
var result = ""
var chars = Array(self)
while i < chars.count {
if fullCharSet.contains(chars[i]) {
var numString = String(chars[i])
i += 1
loop: while i < chars.count {
if fullCharSet.contains(chars[i]) {
numString += String(chars[i])
i += 1
} else {
break loop
}
}
if let num = Double(numString) {
result += "\(num)"
} else {
result += numString
}
} else {
result += String(chars[i])
i += 1
}
}
return result
}
//calculation of string and value returned as double from this function

func calculate() -> Double? {
let transformedString = allNumsToDouble()
let expr = NSExpression(format: transformedString)
return expr.expressionValue(with: nil, context: nil) as? Double
}
}

最佳答案

它可能在线上发生:let expr = NSExpression(format: transformedString)因为您的方法 'allNumsToDouble()' 返回“==1 ”,它可能从标签中获得。

此外,您使用强制展开所有代码 labelOutlet.text!如果标签中没有文本,这可能会导致崩溃。

关于ios - 如果在数字之前按下计算器应用程序中的运算符(operator)按钮,则应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56882328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com