【问题标题】:understand calculator code on Ios [closed]了解 Ios 上的计算器代码 [关闭]
【发布时间】:2016-11-07 19:42:34
【问题描述】:

我想看看程序员是如何解释这段代码的,最后一行的用处是什么? 我是一个新手,我不确定我是否正确理解了这段代码。希望你能给出很好的详细答案,这样我就可以从中受益,也可以让其他新的初学者受益。

var UserIsInTheMiddleOfTyping = false
@IBAction func TouchedDigit(_ sender: UIButton) {
    let digit = sender.currentTitle!
    let CurrentTextinDisplay = Display.text!
    if UserIsInTheMiddleOfTyping {
    Display.text =  CurrentTextinDisplay + digit
    }else{
        Display.text = digit
    }
     UserIsInTheMiddleOfTyping = true
}

}

【问题讨论】:

    标签: ios swift calculator


    【解决方案1】:

    这是基于我对这段代码的解释的简要说明。

    显然,在执行该方法之前,我们不知道用户是否正在输入任何内容,因为该方法可能已经被调用,因此UserIsInTheMiddleOfTyping 可以是truefalse

    var UserIsInTheMiddleOfTyping = false

    当他在计算器上点击一个数字时,TouchedDigit(_ sender: UIButton) 方法被触发。

    创建一个新常量digit 并将其设置为发送者的标题,它是UIButton 的一个实例(标题属性是按钮的显示名称,例如1,2,3..)

    创建了一个新常量 CurrentTextinDisplay,并将其设置为我认为是 UITextField 的内容(展开它,因此不为空)

    让 CurrentTextinDisplay = Display.text!

    如果用户在调用方法之前输入了一些东西(虽然代码实现很糟糕),我们将之前创建的 digit 常量附加到 Display 实例的内容中(我猜)它保存了已经输入的数字.

    如果 UserIsInTheMiddleOfTyping { Display.text = CurrentTextinDisplay + 数字 }

    否则,如果用户正在输入第一个数字,则将Display 实例设置为保存第一个digit

    否则{ Display.text = 数字 }

    在返回方法之前将UserIsInTheMiddleOfTyping 设置为true。 (下次触发该方法时,我们将确定进入 if 语句并附加新数字。)

    UserIsInTheMiddleOfTyping = true

    我个人会将代码缩小如下:

    //There is no need to save in a variable if the user is in the middle of typing
    //Because he will be in this state only when the method is triggered, therefore just shrink as follows:
    
    @IBAction func TouchedDigit(_ sender: UIButton) {
    
        //Safe unwrapping of sender.currentTitle:
        if let actualDigit = sender.currentTitle {
    
            //Safe unwrapping of Display.text:
            if let actualText = Display.text {
    
                Display.text =  actualText + actualDigit
    
    
            }
    
        }
    
    }
    

    希望这会有所帮助,如果有,请将问题标记为正确。

    再见

    【讨论】:

    • 谢谢阿尔伯特。这非常有帮助,我感谢您抽出时间非常详细地解释它。我不知道他们为什么拒绝我的问题,就像他们有一天不是初学者一样。但是非常感谢阿尔伯特。
    • 很高兴我对你有帮助。忘记别人,做你自己。下次尝试更深入地描述您的问题。
    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    相关资源
    最近更新 更多