-5

I have a calculator, but I can´t resolve this code:

@IBAction func calcular(sender: AnyObject) {

    resultado.text = String(format: "", Sliderdosis)

    let peso = pesoLabel.text

    let dosis = dosisLabel.text

    let total = (peso * dosis) * 5 / 250

    /* in this point, the program write:
    Binary operator * cannot be applied to two String operands** */

    resultado.text = total     
}      

Some body help me please? I´m a beginner, sorry!

dfrib
  • 70,367
  • 12
  • 127
  • 192
ValRas
  • 1
  • 2
  • 1
    What language is this? Judging by the error message, I'm guessing swift? Please edit the tags in the question to clarify. – Mooing Duck Jan 11 '16 at 19:50
  • Hi @ValRas. If the answer below has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – dfrib Feb 02 '16 at 18:09

1 Answers1

2

The infix binary operator * does not exist for type String. You are attempting to multiply String objects (that are, inherently, not numerical) hence the error.

I'd suggest you make use of Leo Dabus excellent UITextField extension, however, in your case, extending UILabel (assuming pesoLabel and dosisLabel are UILabel instances)

extension UILabel {
    var stringValue : String { return text                ?? "" }
    var integerValue: Int    { return Int(stringValue)    ?? 0  }
    var doubleValue : Double { return Double(stringValue) ?? 0  }
    var floatValue  : Float  { return Float(stringValue)  ?? 0  }
}

Add this to the header of your .swift file. Thereafter you can update you button action method according to:

@IBAction func calcular(sender: AnyObject) {

    resultado.text = String(format: "", Sliderdosis)

    let peso = pesoLabel.doubleValue
    let dosis = dosisLabel.doubleValue
    let total = (peso * dosis) * 5 / 250

    resultado.text = String(total)   
}

Finally note that this subject is well-covered here on SO, so there exists existing threads that can help you convert string to numerical values. E.g.

Also have a look at the Asking section here on SO, it contains lots of valuable information of how to ask, when to ask, and so on.

Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192