Home > Software design >  Replace array in range
Replace array in range

Time:08-30

I have an array of strings ["", "", "", "1"]

And I want an arrays with all empty strings replaced with zeros - ["0", "0", "0", "1"]

Is there a built-in operator, function or method to help me do this without having to re-invent the wheel?

CodePudding user response:

If your transformation needs strings as result, the comment from TusharSharma provides a solution that answers exactly your question (I'll not repeat it, because I hope he'll enter it as an answer).

However, looking at your example, it seems that you deal with numeric strings. For the records, I'd like to suggest then to simply consider to produce an array of integers.

let s = ["", "", "", "1"]
let r = s.map{Int($0) ?? 0}

If the numbers are doubles:

let r2 = s.map{String(Double($0) ?? 0.0)}

Using the numerics allows you to easily use more advanced build-in formatting:

let r3 = s.map{String(format: "%.2f", Double($0) ?? 0.0)}

or even use some custom number formatter able to use the locales (more here)

  • Related