JimmyLee
JimmyLee

Reputation: 569

How to create increment number string?

Like my question title.
If I get string 00001, I want to +1 and return 00002.
If I get string 00009, I want to +1 and return 00010.
....
If I get string 89999, I want to +1 and return 90000.
How to make this function looks better and easier? Thanks.

func createFloatNumberString(str: String){

    var idArray: [String] = [] //[0,0,0,0,1] [0,0,0,1,0] [8,9,9,9,9]

    str.map { (char) in
        idArray.append(char.description)
    }

    idArray[4] = String(Int(idArray[4])!+1)

    if idArray[4] == "10" {
        idArray[4] = "0"
        idArray[3] = String(Int(idArray[3])!+1)

        if idArray[3] == "10" {
            idArray[3] = "0"
            idArray[2] = String(Int(idArray[2])!+1)

            if idArray[2] == "10" {
                idArray[2] = "0"
                idArray[1] = String(Int(idArray[1])!+1)

                if idArray[1] == "10" {
                    idArray[1] = "0"
                    idArray[0] = String(Int(idArray[0])!+1)
                }
            }
        }
    }
}

Upvotes: 0

Views: 654

Answers (2)

vadian
vadian

Reputation: 285072

Very simple solution:

As counter use an Int and this extension

extension Int {
    var fiveDigitStringRepresentation : String {
        return String(format: "%05ld", self)
    }
}

123.fiveDigitStringRepresentation // "00123"

Or – a bit more sophisticated – use a struct

struct Count {
    var counter = 0

    mutating func increment() { counter += 1 }

    var fiveDigitStringRepresentation : String {
        return String(format: "%05ld", counter)
    }
}


var count = Count()
count.increment()
count.increment()
print(count.fiveDigitStringRepresentation) // "00002"

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54716

You need to convert the String to an Int, increment it, then use a formatted String as the return value.

func incrementFormattedNumericString(numericString:String,increment by:Int=1) -> String? {
    guard let numericValue = Int(numericString) else { return nil }
    return String(format: "%.5ld", numericValue+by)
}

If you are sure that the numericString passed into the function will always be a valid number, you can force unwrap the conversion to Int and return a non-Optional value.

Upvotes: 1

Related Questions