我建議你創建的項目數組,而不是字典的struct
這樣
struct Item{
var itemID : Int
var name : String
init(dictionary:[String:Any]) {
itemID = dictionary["itm_id"] as? Int ?? 0
name = dictionary["itm_name"] as? String ?? ""
}
}
一旦你有Items
陣列可以映射的元素特定項目ID作爲數組來獲取計數並將其從數組中移除。看看下面的代碼。不是最乾淨的實現,但它會幫助你解決問題。
func countDuplicates(){
let dictionary = [["itm_id": 4, "itm_name": "Chicken"],["itm_id": 4, "itm_name": "Chicken"],["itm_id": 4, "itm_name": "Chicken"],["itm_id": 7, "itm_name": "Cat"]]
var items = [Item]()
var countArray = [[String:Any]]()
dictionary.forEach{
items.append(Item(dictionary: $0))
}
while items.count > 0 {
if let firstItem = items.first{
let duplicateItems = items.filter{$0.itemID == firstItem.itemID}
var countDictionary = [String:Any]()
countDictionary["itm_id"] = firstItem.itemID
countDictionary["count"] = duplicateItems.count
countArray.append(countDictionary)
items = items.filter{$0.itemID != firstItem.itemID}
}
}
print(countArray)
}
這將打印[["itm_id": 4, "count": 3], ["itm_id": 7, "count": 1]]
我假定Chicken
,Cat
都是字符串。如果他們不是一個字符串,但一個類類型你可以重寫Item
結構來這樣的事情
class Animal{}
class Chicken:Animal{}
class Cat:Animal{}
struct Item<T:Animal>{
var itemID : Int
var name : String
var animal : Animal
init(dictionary:[String:Any],animal:T) {
itemID = dictionary["itm_id"] as? Int ?? 0
name = dictionary["itm_name"] as? String ?? ""
self.animal = animal
}
}
然後你就可以初始化項目像
yourItem = Item(dictionary:yourDictionary,animal:Cat())
爲你的字典定義「平等」。你只需要'itm_id'匹配,或者'itm_id'和'itm_name'匹配?如果我有'[「itm_id」:4,「itm_name」:Duck]'?它等於'雞肉'嗎?如果你有不同的「雞」呢? –
我建議使用結構而不是字典(如已經回答),使其符合'Hashable'協議,並使用'NSCountedSet'來知道對象在給定集合中重複的次數。 – EmilioPelaez