0

I'm working with a Set of CarCagetory:

public struct Images {
    static let categoryTeaser = UIImage()
}

public enum PremiumModel {
    case model1, model2, model3, unknown 
}

public struct CarCategory {
    public let teaserImage: UIImage
    public let make: String
    public let model: PremiumModel
    public let startPrice: Double
}

// MARK: - Equatable
extension CarCategory: Equatable {
    public static func == (lhs: CarCategory, rhs: CarCategory) -> Bool {
        return lhs.model == rhs.model
    }
}

// MARK: - Hashable
extension CarCategory: Hashable {
    public var hashValue: Int {
        return model.hashValue
    }
}

I'm iterating over an array of Cars and extracting a Set of categories according to the model:

var categories = Set<CarCategory>()

carSpecifications.forEach {
    if PremiumModel(rawValue: $0.car.model) != .unknown {    
        categories.insert(CarCategory(teaserImage: Images.categoryTeaser, make: $0.car.make, model: PremiumModel(rawValue: $0.car.model), startPrice: $0.pricing.price))
    }
}

This works just fine.

Now I want to keep my Set updated with the lowest price for a certain model. I'm thinking on a dictionary of [PremiumModel: Double] where I keep the lowest price for a model and at the end I update my Set accordingly, but I wonder if there is a better way.

Edit:

That's my current implementation using a dictionary. It feels rudimentary...

carSpecifications.forEach {
    let model = PremiumModel(rawValue: $0.car.model)
    if model != .unknown {

        if let value = minPriceForModel[model] {
            minPriceForModel[model] = min(value, $0.pricing.price)
        } else {
            minPriceForModel[model] = $0.pricing.price
        }

        categories.insert(CarCategory(teaserImage: Images.categoryTeaser, make: $0.car.make, model: model, startPrice: $0.pricing.price))
    }
}

let sortedCategories = Array(categories.sorted(by: <))
    .compactMap { (category: CarCategory) -> CarCategory in
    var newCategory = category
    newCategory.startPrice = minPriceForModel[category.model] ?? 0
    return newCategory
}

return sortedCategories
gmoraleda
  • 1,731
  • 1
  • 17
  • 44

0 Answers0