by @codeexamples

Convert int to string with leading zeros in Swift

Home » swift » Convert int to string with leading zeros in Swift

To convert int to a string by adding leading zeros, we can use the Strings init(format:_:) initializer.

Here is an example, that adds leading 0 to the 1.

import Foundation

let str1 = String(format: "%02d", 1);

print(str1);

Output:

01

If you want to add two leading zeros, you can do it like this.

import Foundation

let string0 = String(format: "%03d", 1);
print(string0); // 001