Leading zeros for Int in Swift

Jeehut picture Jeehut · Aug 29, 2014 · Viewed 119.7k times · Source

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?

Answer

vacawama picture vacawama · Aug 29, 2014

Assuming you want a field length of 2 with leading zeros you'd do this:

import Foundation

for myInt in 1 ... 3 {
    print(String(format: "%02d", myInt))
}

output:

01
02
03

This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit.


The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this:

let hours = 3
let minutes = 15
let seconds = 7
print(String(format: "%02d:%02d:%02d", hours, minutes, seconds))

output:

03:15:07