0

In my application i create multiple files and i would like them to have consecutive numbering as part of the name. For example log_0001, log_0002

I use string interpolation, so in code it looks like

fileName = "log_\(number)"
number = number + 1

However, if i keep number as just Int, i will have log_1 instead of log_0001

I've only figured that i could check if number has 1/2/3/4 digits and add '000/00/0' manually.

Are there any String modifications allowing to put the required number of '0' to make it 4 symbols?

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Alice A.
  • 85
  • 1
  • 7

1 Answers1

0

"I've only figured that i could check if number has 1/2/3/4 digits and add '000/00/0' manually."

In this case try the following code: Save the digit length in a variable, for example digitLength.

if (digitLength == 1) { print("log_000") 
} else if (digitLength == 2) { print("log_00")
} else if (digitLength == 3) { print("log_0")
}
else { print("log_") }

print(number)

and then the variable.

Carlos R
  • 205
  • 2
  • 12
  • 1
    Yikes, at least use a `switch`! – Alexander Dec 17 '17 at 22:56
  • you could also try to convert the Int in Swift to a String with leading zeros. – Carlos R Dec 17 '17 at 23:00
  • in this case read here: https://stackoverflow.com/questions/25566581/leading-zeros-for-int-in-swift – Carlos R Dec 17 '17 at 23:01
  • And where does `digit` come from? The question is about a number starting with 1 and incrementing over time. – rmaddy Dec 18 '17 at 00:10
  • Hello @rmaddy, I have change the code, from digit to digitLength, for better understanding. – Carlos R Dec 18 '17 at 15:03
  • OK, then where does `digitLength` come from? – rmaddy Dec 18 '17 at 15:04
  • From the question. Read carefully. :) – Carlos R Dec 18 '17 at 15:14
  • I have read it, that's why I'm asking you. The code in the question is about a number. There is no code showing a digit length. For your answer to be useful, you should show how `digitLength` is calculated from `number`. Of course at this point you may as well delete your answer since the question has been closed as a duplicate. – rmaddy Dec 18 '17 at 16:10
  • He wrote "I've only figured that i could check if number has 1/2/3/4 digits and add '000/00/0' manually." – Carlos R Dec 18 '17 at 21:53