代码之家  ›  专栏  ›  技术社区  ›  Zach

执行算术swift时的可选值

  •  -3
  • Zach  · 技术社区  · 8 年前

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

    不确定为什么会发生这种情况。我的代码附在下面。提前谢谢!

    视图控制器:

    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 回复  |  直到 8 年前
        1
  •  1
  •   David Yang Liu    8 年前

    屏幕text=数字<<<&书信电报;在设置此选项之前,您没有将其展开

    因此输出是可选的(“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
      }
    

    顺便说一句,不要使用IUO来展开,但不在这个问题的范围内 而且你也不需要分号