Ali
Ali

Reputation: 515

Can anybody explain what this simple method is doing, step by step?

This is part of a calculator program

Creating a boolean type variable with a false value to use for our if statement

var userIsInTheMiddleOfTypingANumber: Bool = false

We put the title of the buttons from 0-9 and made the digit variable value equal the button's titles (0-9)and we want the numbers to display in the label's display that we created but we need the 0 (the title of the first button to be removed from the label's display we created, once we start typing digits)

@IBAction func appendDigit(sender: UIButton)
{

    let digit = sender.currentTitle!

    if userIsInTheMiddleOfTypingANumber {

        display.text = display.text! + digit


    }
    else {

   display.text = digit


    userIsInTheMiddleOfTypingANumber = true


    }

}

Upvotes: 1

Views: 117

Answers (2)

ecatalano
ecatalano

Reputation: 687

Let's go through this step by step.

If you think about how a calculator works, if you are typing a completely new number (say you just got an answer and you want to start with a new equation) the entire bar will be erased in place of the new number you are typing.

But this does not occur every time you are typing a number, otherwise the entire bar would only be able to read a single digit.

Your function is:

@IBAction func appendDigit(sender: UIButton)
{

    let digit = sender.currentTitle!

    if userIsInTheMiddleOfTypingANumber {

        display.text = display.text! + digit


    }
    else {

   display.text = digit


    userIsInTheMiddleOfTypingANumber = true


    }

}

the first line:

let digit = sender.currentTitle!

sets the variable digit to the current number is being typed by the user.

The next line,

 if userIsInTheMiddleOfTypingANumber {
          display.text = display.text! + digit
       }

If the user is in the middle of typing a number, the number on screen will append whatever digits the user is typing to the end.

The last part:

    else {

   display.text = digit


    userIsInTheMiddleOfTypingANumber = true


    }

}

Detects that the user is typing a completely new number (starting a new equation possibly), so the text is completely replaced with the first number the user types

The mode is then set to userIsInTheMiddleOfTypingANumber, so that whatever numbers are following the first one will be appended to the end rather than replacing the entire number.

Hope this helps!

Upvotes: 1

Kendel
Kendel

Reputation: 1708

Essentially when you click the first number, it sees that and sets the displays text to that single number. Then, every number typed after that is added to the end of the first digit to create a larger number.

Upvotes: 0

Related Questions