Convert a String to an Integer in Swift


Whether it is iOS development or for any other Apple device, developers often need to convert a string type data of digits (“345”) to an integer (345) using Swift language.

A typical example is when you must get the text from the text field in pure integer form for some mathematical calculation. These types of calculations can not be done with string-type values. So it needs to be converted.

In this tutorial, I am going to let you know how to convert a string to an integer in Swift programming.

Previously in past, Swift provides a method toInt() for converting string values to integers. But this method was removed from the Swift 2.x.

Swift now allows us to use the integer initializer for the conversion of string to integer as you can see below:

Int(myString)

Using integer initializer

As I have just mentioned above, you can use the integer initializer for converting a string to an integer value.

Now see the example below where we are converting a string type value to an integer value:

let myString = "345"

let myInt = Int(myString)

Valid strings

In the example above the string, we provided is a valid string for conversion to an integer. There are limited possibilities available for a string to be valid. It only can form with “+” or “-” sign character followed by one or more numeric digits or all the characters and can be one or more numeric digits.

Below are given these valid strings with the integer conversions:

Int("345")
// 345

Int("+345")
// 345

Int("-345")
// -345

Invalid strings

Now, what will happen if the string contains something invalid as you can see below? If you provide an invalid string, then the value will be nil if you try to convert it to an integer in the same way as you can see in the above examples.

let myString = "345G"

In that case, the integer value will be nil.

Below are some of the invalid strings:

Int(" 345")                       // Includes whitespace
Int("20-23")                      // Invalid format
Int("cc5500")                     // Characters out of bounds
Int("10000000000000000000000000") // Out of range
Int("untitled789")                // Characters out of bounds
Int("567untitled")                // Characters out of bounds
Int("9,345")                      // Characters out of bounds

In that case, you can force a value when the integer becomes nil. Below is how to do it:

let myString = "345G"

let myInt = Int(myString) ?? 0

You can also use the if-let to ensure the value just like you can see below:

if let myInt = Int(" 789") {
    // Your code
}

Below is another example:

if let myInt = Int(" 789") {
   print("Strig is valid")
} else {
    print("String is invalid")
}

In our case, for the above code the output will be:

String is invalid

Using NumberFormatter

Till now, we have used the Swift integer initializer to convert a string into an integer. But for a string that represents curtain format of integer, in that case, you should use NumberFormatter.

Below is the example:

import Foundation

let nf = NumberFormatter()
let myInt = nf.number(from: "345")?.intValue
/// 345

Using the NumberFormatter, the whitespace of the beginning and of the ending is insensitive:

import Foundation

let nf = NumberFormatter()
let myInt = nf.number(from: " 345 ")?.intValue
/// 345

Conclusion

You have learned two different ways for string to integer conversion. You can see that using integer initializer is so straightforward, quick and simple while using NumberFormatter is a little bit of sophisticated task

You should choose the right way in your project when you need to convert a string. I hope this tutorial will be helpful to you.

Also, read: Convert comma-separated string to array in Swift