How to improve this method that compares three numbers?

1

Can you help me improve this little code so it's less extensive and clean?

The code compares three numbers and shows which one is the largest of them:

@IBAction func comprar(_ sender: Any) {

    if pNumero.text! > sNumero.text! {
        messageLabel.text = "Primeiro número e maior"
    }

    else if pNumero.text! < sNumero.text! {
        messageLabel.text = "Segundo número e maior"
    }

    if tNumero.text! > pNumero.text!{
        messageLabel.text = "o Terceiro número e maior"
    }


    else if tNumero.text! < sNumero.text! {
        messageLabel.text = "o Terceiro número e maior"
    }

    else if pNumero.text! == sNumero.text!{
        messageLabel.text = "Os dois números são iguais"

    }
    
asked by anonymous 03.02.2017 / 00:26

1 answer

5

I've never used swift in my life, but I'll come up with an answer.

@IBAction func comprar(_ sender: Any) {

    var maior = pNumero.text!

    messageLabel.text = "Primeiro número e maior"

    if sNumero.text! > maior {
        maior = sNumero.text!
        messageLabel.text = "Segundo número e maior"
    }

    if tNumero.text! > maior {
        maior = tNumero.text!
        messageLabel.text = "Terceiro número e maior"
    }

}

Explanation

You always store the largest value in a variable and compare the others with this value. If the new value is greater, update the variable. In the beginning, the first number is considered to be the largest, because there is no value to compare it. We check if the second value is greater than the first. If yes, maior is set to sNumero , otherwise, it retains the value of pNumero . After that, we check if the third number is greater than maior . If yes, we update the value of maior with the value of tNumero , if not, it retains the current value.

A variation of this code, with the same logic, can be seen running here .

    
03.02.2017 / 00:48