Reputation: 728
I'm extremely new to Swift, and I'm trying to build a simple calculator to test the waters. I have a UILabel with name 'display', and I want to store its value as an int in a variable called 'numA'. However, when I did that, the variable numA gets the value nil.
I discovered why this happened, because when I simply print the display text in the console:
println("\(display.text!)")
I get this: " 6" instead of "6". Notice the additional space appended at the beginning. This is why I cannot do this:
var numA = display.text!.toInt()
What am I doing wrong?
Thanks
Upvotes: 0
Views: 183
Reputation: 154731
The leading space might be there because you are initializing your display
to " "
(a single space) instead of to ""
(empty string). Even if you have spaces in your display.text
, you can trim them out before calling toInt()
.
Note that since toInt()
returns an optional, you should use optional binding to unwrap it to prevent app crashes. I recommend:
if let numA = display.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).toInt() {
// use numA
}
Note the use of ?
after text
instead of !
. This will keep your app from crashing if display.text
is nil
. This is an example of an optional chain; if display.text
is nil
, the entire chain will be nil
.
This can be further simplified by leaving out NSCharacterSet
which Swift can infer from the call:
if let numA = display.text?.stringByTrimmingCharactersInSet(.whitespaceCharacterSet()).toInt() {
// use numA
}
Upvotes: 1