如果在数字前按下计算器应用程序中的操作员按钮,则该应用程序将崩溃

时间:2019-07-04 07:04:41

标签: ios swift

我是Swift的新手,我设计了一个Calculator App,其中如果我在输入数字之前按操作员按钮,该App将崩溃并显示给我

  

错误:由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串“ == 1”'

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NLog;

namespace PumpComm
{
    class Program
    {
        // Event listener
        public static void OnResponseReceived(object source, SocketEventArgs e)
        {
            logger.Info($"Response received: {e.remoteResponse}");

        }

        public static Logger logger = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            IPAddress ipAddress = IPAddress.Parse("192.168.0.102");
            int port = 9003;

            var asyncSocket = new AsyncSocketClient(ipAddress, port);

            asyncSocket.ResponseReceived += OnResponseReceived;

            var result = asyncSocket.StartClient();
            logger.Info($"Connection established: {result}");

            asyncSocket.SendData("$P02Kn\r");

            asyncSocket.StopClient();
        }
    }
}

}

为计算输入的字符串而创建的字符串扩展名

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
}

1 个答案:

答案 0 :(得分:0)

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

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