Yohida Steroflisk Yohida Steroflisk - 25 days ago 15
Swift Question

understand calculator code on Ios

I want to see how programmers explain this code, and What is the utility of the last line?
I am a new beginner and I am not sure if I am understanding this code properly. Hope you are going to give nice detailed answers so I can get my benefit and also the other new beginners ever after.

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
}


}

Answer

This is a brief explanation based on my interpretation of this fragment of code.

Apparently, before the method is executed we don't know if the user is typing anything or not since the method could have been already called, therefore UserIsInTheMiddleOfTyping could be either true or false

var UserIsInTheMiddleOfTyping = false

When he taps a number on the calculator the method TouchedDigit(_ sender: UIButton) is triggered.

A new constant digit is created and set to the sender's title which is an instance of UIButton (The title property is the displayed name of the button, e.g. 1,2,3..)

A new constant CurrentTextinDisplay is created and set to the content of what I suppose to be a UITextField (Unwrapping it, therefore is not null)

let CurrentTextinDisplay = Display.text!

If the user was typing something before the method was called (Pretty bad code implementation though), we append the digit constant created before to the content of the Display instance which (I guess) holds the digits already typed.

if UserIsInTheMiddleOfTyping { Display.text = CurrentTextinDisplay + digit }

Otherwise, if the user is entering the first digit, whe set the Display instance to hold this first digit

else{ Display.text = digit }

Before returning the method sets UserIsInTheMiddleOfTyping to true. (Next time the method is triggered we will enter the if statement for sure and append the new digit.)

UserIsInTheMiddleOfTyping = true

I would personally shrink as follows:

@IBAction func TouchedDigit(_ sender: UIButton) {

    let digit = sender.currentTitle!
    let CurrentTextinDisplay = Display.text!

    Display.text =  CurrentTextinDisplay + digit

}

Hope this helped, if so mark the question as correct.

Bye

Comments