做算术快速时的可选值

时间:2016-02-09 01:33:48

标签: ios swift calculator optional

我正在使用swift for iOS创建一个计算器应用程序。当我输入一个大于9的数字时,我得到以下输出(例如当我输入10时)enter image description here

不确定为什么会这样。我的代码附在下面。提前谢谢!

的ViewController:

class ViewController: UIViewController {
    @IBOutlet weak var Screen: UILabel!
    var firstNumber = Float()
    var secondNumber = Float()
    var result = Float()
    var operation = ""
    var isTypingNumber = false

    @IBAction func Dot(sender: AnyObject) {
        var dot = sender.currentTitle

        Screen.text = Screen.text! + dot!!
    }
    @IBAction func Number(sender: AnyObject) {
        var number = sender.currentTitle
        if isTypingNumber == true {
            Screen.text = Screen.text! + number!!;
        } else {
            Screen.text = number;
        }
        isTypingNumber = true
    }
    @IBAction func Operation(sender: AnyObject) {
        operation = sender.currentTitle!!
        isTypingNumber = false
        firstNumber = (Screen.text! as NSString).floatValue
    }
    @IBAction func Equals(sender: AnyObject) {
        secondNumber = (Screen.text! as NSString).floatValue
        isTypingNumber = false
        if operation == "+" {
            result = firstNumber + secondNumber;
        } else if operation == "-" {
            result = firstNumber - secondNumber;
        } else if operation == "x" {
            result = firstNumber * secondNumber;
        } else if operation == "/" {
            result = firstNumber / secondNumber;
        } else if operation == "%" {
            result = (firstNumber * secondNumber) / 100
        } else if operation == "√" {
            result = sqrt(firstNumber)
        }
        Screen.text = "\(result)"
    }
    @IBAction func Clear(sender: AnyObject) {
        firstNumber = 0
        secondNumber = 0
        result = 0
        Screen.text = "\(0)"
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

1 个答案:

答案 0 :(得分:1)

Screen.text = number; <<<<在设置之前你没有打开这个可选项

因此输出是可选的(" 0")

 @IBAction func Number(sender: AnyObject) {
    var number = sender.currentTitle
    if isTypingNumber == true {
      Screen.text = Screen.text! + number!!;
    } else {
      Screen.text = number; <<<< you did not unwrap this optional before setting it
    }
    isTypingNumber = true
  }
<> BTW不要使用IUO来解开,但不在此问题的范围内 你也不需要分号