Search code examples
iosswift4cart

How To multiple Euro values total arrays in ios Swift 5 Like ["£179.95", "£199.95", "£89.95"]


array = ["£179.95", "£199.95", "£89.95"]

How to multiple this values add get the total values in ios swift 4.

Please help me.


Solution

  • If you're sure that the strings contained in your array always start with a £, you could do this:

    let sum = array.compactMap { Double($0.replacingOccurrences(of: "£", with: "")) }
                   .reduce(0.0, { $0 + $1 })
    

    Example:

    let array = ["£179.95", "£199.95", "£89.95"]
    let sum = array.compactMap { Double($0.replacingOccurrences(of: "£", with: "")) }
                   .reduce(0.0, { $0 + $1 })
    print(sum) // 469.84999999999997