我正在与以下Set
人员合作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
}
}
我正在遍历 Cars 数组并根据模型提取一组类别:
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))
}
}
这工作得很好。
现在我想用某个型号的最低价格更新我的套装。我正在考虑一本关于[PremiumModel: Double]
我在哪里保持模型最低价格的字典,最后我相应地更新了我的 Set,但我想知道是否有更好的方法。
编辑:
那是我当前使用字典的实现。感觉很初级。。。
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