Converting and Formatting Strings in Swift
In this article, we'll look at how to convert and format strings in Swift.
Formatting Numbers as Strings
To convert numeric values such as Double into formatted strings in Swift, you can use the String initializer.
For example, if you want to format a Double to show only two decimal places, you can write the code as follows.
Since the second argument is handled through Foundation, you need to import it.
import Foundation
let value1: Double = 1234.5678
print(String(format: "%.0f", value1))
print(String(format: "%.1f", value1))
print(String(format: "%.2f", value1))
let value2: Double = 10
print(String(format: "%.0f", value2))
print(String(format: "%.1f", value2))
print(String(format: "%.2f", value2))
The output is as follows. The values are rounded:
1235
1234.6
1234.57
10
10.0
10.00
Converting Strings to Numbers
To convert a numeric string into a number in Swift, you can use the initializer of the numeric type.
For example, to convert a string into a Double, you can do it like this.
The return value is an Optional, so if the conversion fails, it will return nil.
let s1 = "12345.678"
let d1 = Double(s1)
print(d1 ?? "Invalid Input")
let s2 = "ABC"
let d2 = Double(s2)
print(d2 ?? "Invalid Input")
The output is as follows:
12345.678
Invalid Input
Formatting Dates as Strings
To convert a date into a formatted string in Swift, you can use DateFormatter.
For more details, see: How to Convert a Date to a Formatted String in Swift.
Converting Strings to Dates
To convert a string (String) into a date (Date) in Swift, you can also use DateFormatter.
Since DateFormatter is part of Foundation, you need to import it.
import Foundation
let dateString = "2021-10-22 22:34:54"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = df.date(from: dateString) {
print(date)
print(type(of: date))
print(df.string(from: date))
}
The output is as follows:
2021-10-23 05:34:54 +0000
Date
2021-10-22 22:34:54
On line 5, we create a DateFormatter, and on line 6 we set the dateFormat to match the input string.
On line 8, we use the date method of DateFormatter to convert the string into a Date. If the conversion fails, it returns nil.
The first line of the output shows the Date object printed directly, which defaults to UTC. Since I'm in Los Angeles, the offset is +7 hours, shown as +0000. You can configure the locale and time zone in DateFormatter if needed.
The second line confirms that the date variable is of type Date. The third line shows the date converted back into a string using the same DateFormatter.
That's it for converting and formatting strings in Swift.