Convert String to Int (and Back) in Swift
How do you convert a String
to an Int
? The Swift programming language is strong-typed, and that means you can’t type cast between types that aren’t related. Fortunately, many of Swift’s types can be converted from and to strings. Let’s find out how!
Here’s what we’ll get into in this tutorial:
- How to convert from
String
toInt
- How to convert from
Int
toString
- How to use the printf-style
String(format:)
Ready? Let’s go.
- Convert String to Int in Swift
- Convert Int to String
- Convert (Almost) Anything to String
- Further Reading
Convert String to Int in Swift
An obvious scenario in which you’ll need to convert a string to Int
, is when a numeric value (accidentally) is part of a string. How do you get the number out?
Let’s look at an example of how you can convert a string to an int:
let ageInt = Int(ageString)
print(ageInt)
print(type(of: ageInt))
In the above code, a constant ageString
of type String
is initialized with the string literal "42"
. You need this value as an Int
, not as a string.
So, on line 2 you use the Int()
initializer and provide ageString
as its parameter. A new integer is created by using the string.
The ageInt
constant in the example above is an optional. The initializer will return nil
if the provided string can’t be converted to an integer. For example, the string "Bob"
cannot be converted to an integer.
When looking at the Swift documentation for Int, we see that Int
can deal with a great number of types: Double
, Float
, CGFloat
, NSNumber
, String
, and so on. You can pass these types into the Int()
initializer, and get a neatly converted integer back. (It usually works the other way too.)
Why do you need to convert "42"
to 42
in the first place? Well, to us it may seem that these numbers are exactly the same, but to the Swift compiler they’re entirely different things. The former is a string of characters, like "abcd"
, and the latter is a numeric value, like 999
.
It’s easiest to compare it to writing “forty-two” and “42”. Even though those words have exactly the same meaning, they’re written differently. The Swift compiler is so exact in it’s execution that it gives both versions a different designation – a type – and that means we’ll need to convert one to the other, if needed.
It’s worth noting that the Int()
initializer for strings only accepts string values with numbers from 0
to 9
, and -
or +
, and nothing else. Passing mathematical expressions, such as 5.316912e+36
, won’t work. And neither will a string with a space, i.e. " 42"
. If you’re looking to convert a complex number string to a number value, check out NumberFormatter.
Convert Int to String
What about converting an Int
to a String
? It’s exactly the opposite of what we did before. Instead of getting an integer value out of a string, now we’re going to put one into a string.
Here’s an example of converting an int to a string in Swift:
let ageString = String(ageInt)
print(ageString)
print(type(of: ageString))
In the above code, a constant ageInt
of type Int
, with value 42
, is provided to the String()
initializer. Its result is assigned to ageString
, a constant with the type String
.
A similar thing to what we’ve seen before happens. The integer value is provided as a parameter to the String()
initializer, which converts it into a String
.
Sometimes, you’ll see this conversion from int to string:
let ageInt = 42
let ageString = "\(ageInt)"
print(ageString)
In the above example, a Swift feature called string interpolation is used to convert the ageInt
integer value to a string. The constant is wrapped in \(
and )
within the string. You’re effectively using the ageInt
constant as a “placeholder” in the string.
Although this approach is technically correct, it’s better to use the String()
initializer as shown before. String interpolation is a great feature to combine several values in a string, though. Like this:
print("This post has \(like_count) likes and \(comment_count) comments.")
Everything between \(
and )
is evaluated as an expression, so you can also code something like:
let apples = 3
let oranges = 2
print("We have \(apples + oranges) pieces of fruit.")
// Output: We have 5 pieces of fruit.
And that’s a segway for what we’ll look at next: converting (almost) anything to strings.
You can pass almost any number value in String()
, Int()
, Double()
, and so on. You might lose precision though, so keep that in mind!
Convert (Almost) Anything to String
When a class or struct adopts the CustomStringConvertible
protocol, it can be printed out as a string.
Let’s look at an example:
{
var name:String = ""
var description:String {
return name
}
}
var car = Vehicle()
car.name = "Pontiac Firebird"
print("Bob and Alice are driving in their \(car)")
The above code isn’t exactly converting the Car
struct to String
, but it’s providing a string representation that describes the object using the description
property. When the car
object is printed, using string interpolation, the description
property is implicitly accessed and used to create the string.
Another great approach to turn objects and values into strings is by using String(format:)
. Instead of constructing a string from a value directly, you can provide a format that’s used to describe the object.
Here’s an example:
let pi = String(format: "%.5f", Double.pi)
print(pi)
// Output: 3.14159
The above code prints out π
(pi) with 5 decimal places, by using the format %.5f
. This formatting style is taken from the ISO C standard for printf.
You can use a number of specifiers to format values and objects:
-
%@
for objects (and strings) -
%d
for integers -
%f
for doubles
Use as many parameters as you want, optionally putting them in an array. The format is read left-to-right. Here’s another example:
String(format: "%d, %d, %@", 1, 2, "three")
// "1, 2, three"
String(format: "%@, %d, %@", arguments: ["five", 6, "seven"])
// "five, 6, seven"
The n$
specifier refers to a value with a specific index. See how the order of arguments is changed, in the code below?
String(format: "%2$@ %1$@", "world!", "Hello")
// "Hello world!"
Last but not least, you can use modifiers to change the padding and precision of a specifier. Here’s how to specify the precision of a number:
String(format: "%.5f", Double.pi)
// "3.14159"
The 5
in %.5f
prints out a double-precision floating-point value (a so-called “double”) with 5 decimal places. And here’s how to pad a number:
String(format: "%02d", 3)
// "03"
The 02
in %02d
prints out the number 3
with a minimum of 2 digits, optionally padding them on the left with zeroes. This is handy if you want to ensure that a printed number always has a given width.
Quick Tip: If you’re dealing with dates, times or currency values, consider using DateFormatter or NumberFormatter instead of String(format:)
. It’s easier, less prone to errors and takes a user’s locale into account.
Further Reading
Now you know how to convert strings to integers, and vice versa. We’ve also discussed how you can use String(format:)
to better format strings.
Converting between values seems counter-intuitive at first, once you realize that most of Swift’s primitive number values can effortlessly convert between types. Awesome!
Want to learn more? Check out these resources: