Leading zeros for Int in Swift

2019-01-01 08:45发布

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?

8条回答
伤终究还是伤i
2楼-- · 2019-01-01 09:21

in Xcode 8.3.2, iOS 10.3 Thats is good to now

Sample1:

let dayMoveRaw = 5 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05

Sample2:

let dayMoveRaw = 55 
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55
查看更多
千与千寻千般痛.
3楼-- · 2019-01-01 09:22

The other answers are good if you are dealing only with numbers using the format string, but this is good when you may have strings that need to be padded (although admittedly a little diffent than the question asked, seems similar in spirit). Also, be careful if the string is longer than the pad.

   let str = "a str"
   let padAmount = max(10, str.count)
   String(repeatElement("-", count: padAmount - str.count)) + str

Output "-----a str"

查看更多
登录 后发表回答