I'd like to convert an Int
in Swift to a String
with leading zeros. For example consider this code:
for myInt in 1...3 {
print("\(myInt)")
}
Currently the result of it is:
1
2
3
But I want it to be:
01
02
03
Is there a clean way of doing this within the Swift standard libraries?
Swift 3.0+
Left padding
String
extension similar topadding(toLength:withPad:startingAt:)
inFoundation
Usage:
Assuming you want a field length of 2 with leading zeros you'd do this:
output:
This requires
import Foundation
so technically it is not a part of the Swift language but a capability provided by theFoundation
framework. Note that bothimport UIKit
andimport Cocoa
includeFoundation
so it isn't necessary to import it again if you've already importedCocoa
orUIKit
.The format string can specify the format of multiple items. For instance, if you are trying to format
3
hours,15
minutes and7
seconds into03:15:07
you could do it like this:output:
With Swift 4, you may choose one of the three examples shown below in order to solve your problem.
#1. Using
String
'sinit(format:_:)
initializerFoundation
provides SwiftString
ainit(format:_:)
initializer.init(format:_:)
has the following declaration:The following Playground code shows how to create a
String
formatted fromInt
with at least two integer digits by usinginit(format:_:)
:#2. Using
String
'sinit(format:arguments:)
initializerFoundation
provides SwiftString
ainit(format:arguments:)
initializer.init(format:arguments:)
has the following declaration:The following Playground code shows how to create a
String
formatted fromInt
with at least two integer digits by usinginit(format:arguments:)
:#3. Using
NumberFormatter
Foundation provides
NumberFormatter
. Apple states about it:The following Playground code shows how to create a
NumberFormatter
that returnsString?
from aInt
with at least two integer digits:For left padding add a string extension like this:
Swift 2.0 +
Swift 3.0 +
Using this method:
Details
Xcode 9.0.1, swift 4.0
Solutions
Data
Solution 1
Solution 2
Solution 3
Unlike the other answers that use a formatter, you can also just add an "0" text in front of each number inside of the loop, like this:
But formatter is often better when you have to add suppose a designated amount of 0s for each seperate number. If you only need to add one 0, though, then it's really just your pick.