我有一个格式如下的数组:
[“裤子:15.50”,“裤子:15.50”,“套头衫:12.99”,“鞋子:50.00”]
我想这样格式化:
[“2x 裤子:31.00”,“1x 套头衫:12.99”,“1x 鞋子:50.00”]
我试过用这个格式化:
var counts: [String:Int] = [:]
var shoppingList = ["Trousers : 15.50", "Trousers : 15.50", "Jumper : 12.99", "Shoes: 50.00"]
var formattedShoppingList = [String]()
for item in shoppingList {
counts[item] = (counts[item] ?? 0) + 1
}
for (key, value) in counts {
let display:String = String(value) + "x " + key
formattedShoppingList.append(display)
}
但是我明白了
[“2x 裤子:15.50”,“1x 套头衫:12.99”,“1x 鞋子:50.00”]
如果我使用字典,则不能有重复项。我该如何处理?
最佳答案
我会制作一个结构来表示商品名称/价格对(以及 future 可能的其他数据,例如库存数量)。
struct Item: Hashable {
let name: String
let price: Double
public var hashValue: Int { return name.hashValue ^ price.hashValue }
public static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.name == rhs.name && rhs.price == rhs.price
}
}
let shoppingList = [
Item(name: "Trousers", price: 15.50),
Item(name: "Trousers", price: 15.50),
Item(name: "Jumper", price: 12.99),
Item(name: "Shoes", price: 50),
]
let counts = shoppingList.reduce([Item: Int]()){counts, item in
var counts = counts
counts[item] = (counts[item] ?? 0) + 1
return counts
}
let formattedShoppingList = counts.map{ item, count in "\(count)x \(item.name): £\(item.price)" }
print(formattedShoppingList)
["2x Trousers: £15.5", "1x Shoes: £50.0", "1x Jumper: £12.99"]
关于arrays - 像购物 list 一样格式化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403537/