我有一個數組格式如下:格式就像一個購物清單的陣列
["Trousers : 15.50", "Trousers : 15.50", "Jumper : 12.99", "Shoes: 50.00"]
我想這樣來格式化:
["2x Trousers : 31.00", "1x Jumper : 12.99", "1x Shoes: 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 Trousers : 15.50", "1x Jumper : 12.99", "1x Shoes: 50.00"]
如果我使用一本字典,我不能有重複。我該如何着手解決這個問題?
我*猜測*是'VAR shoppingList = [ 「褲子:15.50」, 「褲:15.50」, 「跳線:12.99」, 「鞋:50.00」]' –
我將所有這些數據分組在一個'struct'或'class'中,而不是使用字典,那麼你可以使用一些屬性來獲得你的項目的大小。 '結構分組{var Key:String var values:[String]}' – Lamar
你知道'[褲子:15.50,褲子:15.50,跳線:12.99,鞋子:50.00]'不是數組嗎? – Alexander