Search code examples
arraysswiftstring-parsing

Calculate of prices in within an array of strings Array<String>


I have an array that describes a list of auto parts (Swift/IOS,array already in such structure arrived from other source.):

let parts = [
    "Wheel = 230$",
    "Door = 200$",
    "Wheel = 300$",
    "Seat = 150$",
    "Seat = 150$",
    "Rugs = 100$"]

I need to calculate the sum of the prices of the auto parts for each type of part. Here's the result I'm looking for:

let expectedResult = [
    "wheel 530$",
    "Door 200$",
    "Seat 300$",
    "Rugs 100$"
]

I don’t understand how to do it.


Solution

  • Here is a solution where I loop through the array and split each element on "=" and then sum the values together using a dictionary. Once that is done the dictionary is converted back to an array

    let parts = [
        "Wheel = 230$",
        "Door = 200$",
        "Wheel = 300$",
        "Seat = 150$",
        "Seat = 150$",
        "Rugs = 100$"]
    
    var values = [String: Int]() // Used to calculate totals per part
    
    parts.forEach { string in
        let split = string.split(separator: "=")
    
        // Make sure the split worked as expected and that we have an integer value after the =
        guard split.count == 2,
              let value = Int(String(split[1]).trimmingCharacters(in: .whitespaces).dropLast()) else { return }
    
        let key = String(split[0]).trimmingCharacters(in: .whitespaces)
    
        // Sum values over the part name
        values[key, default: 0] += value
    }
    
    // Convert back to an array of strings
    let output = values.map { "\($0.key) \($0.value)$"}
    
    print(output)