在swift& amp;中使用bool的目的程序粉碎

时间:2015-06-27 07:08:07

标签: swift ios8

我在线观看斯坦福iOS8课程,我对使用bool的目的有疑问。

第一部分是关于创建计算器。本节的第一课是关于在计算器的屏幕上显示用户按下的数字。教师指出,为了显示没有附加到每个数字开头的零的数字,程序应该有这个布尔变量。

var userIsInTheMiddleOfTypyingANmuber: Bool = false

但是,我真的不明白它在这个程序中是如何工作的,或者教师为什么这样使用它。有人可以帮我解释一下吗?为什么我的程序在按下键盘上的任意两个数字后会崩溃?提前谢谢!

我会添加图片,但我不能,因为我没有足够的声望点。

使用布尔变量之前的显示屏幕如下所示: 0567

使用布尔变量后的显示屏幕如下: 567

import UIKit

class ViewController: UIViewController
{

    @IBOutlet weak var display: UILabel!


    var userIsInTheMiddleOfTypyingANmuber: Bool = false


    @IBAction func appendDigit(sender: UIButton) {

        let digit = sender.currentTitle!

        if userIsInTheMiddleOfTypyingANmuber {

           display.text = display.text! + digit

        } else {

            display.text = digit

            userIsInTheMiddleOfTypyingANmuber = true

        }
    }

2 个答案:

答案 0 :(得分:0)

您没有在代码中解决零0的情况。这就是布尔所用的。如果userIsInTheMiddleOfTypingtrue,则表示您在输入的开头

在伪代码中思考:

if userIsTypingFirstDigit (that is, userIsInTheMiddleOfTyping == false)  
   if digitIsZero
      add the zero to the input text
      (but leave userIsInTheMiddleOfTyping as false) 
   else 
      replace the input text with the digit (which replaces any zeros typed)
      set userIsInTheMiddleOfTyping to true
else
   add the digit to the input text (including zeros)

快乐的编码。

答案 1 :(得分:0)

1)关于

var userIsInTheMiddleOfTypyingANmuber: Bool = false 

此处userIsInTheMiddleOfTypyingANmuber(一个flag变量)是为了确保每次开始输入数字时都重置display标签。

例如,要计算12345 + 789

  

1)输入1。 ---->最初,flag false ,因此display = 1

     

2)继续输入2345 ----> flag现在是 true ,然后是display =   12345

     

3)输入+ ---->将flag重置为 false

     

4)输入7 ---->由于flag false ,因此display =   7(那是让12345消失,重置)                  否则,display将为123457(错误!!!)。

     

5)继续输入89 ----> flag现在 true ,然后display = 789

2)关于崩溃, 因为没有相关的错误消息信息,所以很难说。 但是,基本上,要确保所有Label Button控制器与ViewController连接良好,否则会导致崩溃。