DanteDeveloper
DanteDeveloper

Reputation: 287

Swift - adding values captured in two textfields

I seem to have a problem with a very simple scenario.

I'm trying to add values captured by two text fields (called T1 and T2) and display their total upon pressing a button (GoButton) on a label (Label1).

I tried wording the syntax in multiple ways and it still doesn't work. I feel that some of the syntax I found on the web didn't work for me. I use Xcode 6.3 on Yosemite.

Screenshot: enter image description here

Is there a chance that there is something I'm missing with my Xcode to accept swift syntax? Please help.

Upvotes: 1

Views: 4583

Answers (4)

Mahendra Vishwakarma
Mahendra Vishwakarma

Reputation: 494

Label1.text = "\(T1.text.toInt()! + T2.text.toInt()!)" //T1.text.toInt()

is an optional so you should use ! mark otherwise it will return nil value

Upvotes: 0

Hairgami_Master
Hairgami_Master

Reputation: 5539

Dante- There's still a chance the values could be nil. You've correctly !'ed the TextFields so they unwrap automatically, but the Int conversion is also Optional (the Int still thinks it may get a nil value).

Label1.text = "\(T1.text.toInt()! + T2.text.toInt()!)"

Helpful Hint- If you paste your code in here (rather than a screenshot) it's much easier for folks to copy and paste your code into their IDE and test it out.

For those here smarter than me (everyone) I'm curious why Xcode doesn't complain about a single Int conversion:

Label1.text = "\(T1.text.toInt())"  // no complaint from the compiler

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236548

Thats because toInt() returns an optional value. You can cast your String to NSString and extract the integer value without returning an optional.

Label1.text = ((T1.text! as NSString).integerValue + (T2.text! as NSString).integerValue + (T3.text! as NSString).integerValue + (T4.text! as NSString).integerValue).description 

Upvotes: 1

Mustafa Ibrahim
Mustafa Ibrahim

Reputation: 1120

Value T1.text.toInt() is an Optional Integer. So you must unwrap it first. So use Label1.text = "\(T1.text.toInt()! + T2.text.toInt()!)"

Good luck

Upvotes: 1

Related Questions