凤凰求蛊
对于左边填充,添加如下字符串扩展名: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
}}使用此方法:for myInt in 1...3 {
print("\(myInt)".padLeft(totalWidth: 2, with: "0"))}