Parsing Int Variables in Swift - Optionals and Approaches
/Working with integer numbers in Swift is a little different, since the only string parsing method is toInt() and it returns an optional Int? value.
This means that you have to test the value before you use it, or it could be nil. Doing a force unwrap can result in a crash if you try to use the value.
Below are two approaches you can leverage using the if/else statements.
Approach 1
if let width = widthTextField.text.toInt() {
if let height = heightTextField.text.toInt() {
// Valid user input parsed
println("Valid width: \(width), height: \(height)")
}
}
Approach 2
var width = widthTextField.text.toInt()
var height = heightTextField.text.toInt()
if(width != nil && height != nil) {
// Valid user input parsed
println("Valid width: \(width!), height: \(height!)")
}
The benefit of the second approach is that you can test multiple optionals in a single line. You don't have to nest tons of if/else statements to make sure the values are valid.
I'd like there to be a better approach, but these are the two that I discovered from playing around with optionals. It would be nice if I could use the tuple syntax from a switch statement with the if let keyword.
Double Approach
Working with Double parsing is a different story. It doesn't look like their is a method on String, so you have to cast it to an NSString to convert. Going down that route you lose the Optional values. Invalid casts will return 0.
var width = (widthTextField.text as NSString).doubleValue
A Better Double Approach
The above code doesn't fail elegantly with optional values, and instead may give strange results. Use the NSNumberFormatter and get the double value from the NSNumber object it creates.
var numberFormatter = NSNumberFormatter()
var userInputString = "10.33a0" // 10.33
if let number = numberFormatter.numberFromString(userInputString)?.doubleValue {
println("Converted user input: \(number)")
} else {
println("Invalid number: \(userInputString)")
}
Connect
- Do you have a better approach?
- Subscribe to my mailing list and get a free Swift video course.
- I'm teaching an online Swift iPhone app course.