gpt4 book ai didi

swift - 在 Swift 和 Programrush 中使用 bool 的目的

转载 作者:行者123 更新时间:2023-11-30 14:16:38 25 4
gpt4 key购买 nike

我正在在线观看斯坦福 iOS8 类(class),我有一个关于使用 bool 的目的的问题。

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

var userIsInTheMiddleOfTypyingANmuber: Bool = false

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

我本来可以添加图片,但我不能,因为我没有足够的声誉点。

使用 bool 变量之前的显示屏幕是这样的:第0567章

使用 bool 变量后的显示屏幕将是这样的:第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

}
}

最佳答案

您没有解决代码中零 0 的情况。这就是 bool 值的用途。如果 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)

祝你编码愉快。

关于swift - 在 Swift 和 Programrush 中使用 bool 的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31086152/

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