For left padding add a string extension like this:
Swift 2.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count
if toPad < 1 { return self }
return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
}
}
Swift 3.0 +
extension String {
func padLeft (totalWidth: Int, with: String) -> String {
let toPad = totalWidth - self.characters.count
if toPad < 1 { return self }
return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
}
}
Using this method:
for myInt in 1...3 {
print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}