konya
konya

Reputation: 161

Convert NULL, NaN and not a numeric character to Double

I have a String array as follows and try to convert it to Double array.

There are three issues in the following String array, first two are NULL and NaN and the third one is I have not numeric character in the 2O6.O115, it is not 206.0115.

Please imagine that I have half million data points.

let data = ["2230.01", "NULL", "NaN", "2O6.O115"]

My approach is as follows, but wondering are there any better handling or any suggestion?

let dataInDouble = data.compactMap{Double($0)}.filter{!$0.isNaN}

Upvotes: 0

Views: 322

Answers (1)

timbre timbre
timbre timbre

Reputation: 13960

I think your implementation is OK, but another option is to create a helper function, which allows you to

  • Avoid additional loops / filter chaining
  • Add any rules / corrections to input data you want, like replacing O with 0
func doubleOrNothing(_ string: String) -> Double? {

    let maybeDouble = string.uppercased().replacingOccurrences(of: "O", with: "0")

    guard let d = Double(maybeDouble), !d.isNaN else {
        return nil
    }
    return d
}

// ...

let dataInDouble = data.compactMap { doubleOrNothing($0) }

Upvotes: 1

Related Questions