In Swift I have a string where a dash needs to be inserted after every 3 characters, if there are 4 characters or 2 characters at the end of the string they should be shown as "-xx-xx" or "-xx" respectively.
E.g "203940399345" to "203-940-399-345"
"2039403993454" to "203-940-399-34-54"
"20394039934546" to "203-940-399-345-46"
"2039403993454699409399" to "203-940-399-345-469-940-93-99"
I have the following solution:
func format(_ unformatted:String) -> String {
var formatted = ""
let count = unformatted.characters.count
unformatted.characters.enumerated().forEach {
if $0.offset % 3 == 0 && $0.offset != 0 && $0.offset != count - 1 || $0.offset == count - 2 && count % 3 != 0 {
formatted += "-" + String($0.element)
return
}
formatted += String($0.element)
return
}
return formatted
}
It will add a dash before each third char unless it is the first or last char or it is two from the end but only if the char count is divisible by 3 then it adds a char to the formatted string as normal.
Is there a more optimal way to achieve this formatting? What approach should I be taking with this kind of problem?