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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Yikes, at least use a switch!
you could also try to convert the Int in Swift to a String with leading zeros.
And where does digit come from? The question is about a number starting with 1 and incrementing over time.
Hello @rmaddy, I have change the code, from digit to digitLength, for better understanding.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.