0

i have a problem on Xcode7 i want to add some numbers from a text box with an integer i already have but this code seems not to be working:

@IBAction func ConvertAction(sender: AnyObject) {

    //get the user input

     let Celcius:String? = Textinput.text

    //here
    //here is the problem
    // convert celcius to fahrenheit

    let fahrenheit:Int = ( Celcius + 160 )

//this gives me an error saying "Binary operator "+" cannot be applied to operands of type string? and Int"

    //print on label the farenheit
    Labeloutput.text = "\(Celsius) Celcius is /(fahrenheit) Fahrenheit"

}
St33v3n
  • 39
  • 2

1 Answers1

0

This should work:

let Celcius:String = Textinput.text

if  let celc = Int(Celcius) {
    let fahrenheit:Int = ( celc + 160 )
    Labeloutput.text"\(celc) Celcius is \(fahrenheit) Fahrenheit"
} else {
    print("Computer says no!")
}
arled
  • 2,577
  • 6
  • 27
  • 49
  • Unless of course the input can't be converted to an integer in which case an exception wil be thrown – Paulw11 Nov 01 '15 at 02:29
  • @Paulw11 You were absolutely right. The original answer was assuming that only numbers were being typed (maybe using the numberPad) However, I've updated the answer to be more robust. Im sure there's probably a few ways of handling this though. Thanks. – arled Nov 01 '15 at 02:46
  • Thank you Paulw11 ! it worked!! – St33v3n Nov 02 '15 at 17:57
  • @St33v3n you're welcome - please mark it as the accepted answer. – arled Nov 03 '15 at 09:57