-1

I'm fetching value from RealmDB which is in string format. However this string contains values in arithmetic format like below

let values = ["1/2","1/3","2/3","3/5","1/7"]

Now my problem is that I've to return the addition value of whole array. I'm unable to convert it to Double value because the string itself contain arithmetic operator. How to perform addition on above array of string?

I've tried to use NSExpreesion to do the mathematical operation but it's giving nil value.

let expn = NSExpression(format:"1/3")
print(expn.expressionValue(with: nil, context: nil))
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Jay Savsani
  • 299
  • 1
  • 3
  • 16

1 Answers1

1

You can use a single flatMap on your array to convert the fractional Strings to Doubles. You just have to separate the String into two parts by using String.componenets(separatedBy:), then try converting the String parts into numbers and if that succeeds, do the division.

The "" default value is used during the conversion to Int to make sure your app doesn't crash even if some of the values in the array are not proper fractions.

let fractionStrings = ["1/2","1/3","2/3","3/5","1/7"]
let fractions = fractionStrings.flatMap({ fractionString -> Double? in
    let numbers = fractionString.components(separatedBy: "/")
    if let nominator = Int(numbers.first ?? ""), let denominator = Int(numbers.last ?? "") {
        return Double(nominator)/Double(denominator)
    } else {
        return nil
    }
})
print(fractions)

Output:

[0.5, 0.3333333333333333, 0.6666666666666666, 0.6, 0.1428571428571428]

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116