[英]Realm iOS: count the distinct objects in a collection
獲取表中唯一值計數的最有效方法是什么?
例如:
fruitType
---------
banana
banana
apple
apple
apple
香蕉:2個 蘋果:3個
通過使用fruitsCollection.distinct(by: ["fruitType"])
我可以獲得不同的值但不是計數。
任何幫助,將不勝感激。
你可以嘗試這樣簡單的事情(假設水果是字符串,相應地調整你的 object 類型):
let fruits = fruitsCollection.distinct(by: ["fruitType"])
var results = [String:Int]()
Set(fruits).forEach{ fruit in results[fruit] = (fruits.filter{$0 == fruit}).count }
print("---> results: \(results)")
或者
let results: [String:Int] = Set(fruits).reduce(into: [:]) { dict, next in
dict[next] = (fruits.filter{$0 == next}).count }
print("---> results: \(results)")
Set(fruits)
為您提供了一組獨特的fruit
名稱。 filter{...}
為您提供每個的計數。 forEach
或reduce
將結果轉換為鍵值字典。
@workingdog 的回答非常有效,但這里有一個更真實的選項。 需要記住的是 Realm 結果對象是延遲加載的——這意味着處理非常大的數據集對 memory 的影響很小。
然而,一旦使用高級 Swift 函數,這種惰性就會消失,每個 object 都會吞噬 memory。
例如,將 50,000 個 Realm 對象加載到結果object 中不會產生任何顯着的 memory 影響 - 但是,將 50,000 個對象加載到數組中可能會使設備不堪重負,因為對象失去了它們的延遲加載特性。
使用此解決方案,我們依靠 Realm 來呈現唯一值並將它們存儲在結果中(惰性),然后迭代我們過濾匹配對象(惰性)並返回它們的計數。
我創建了一個 FruitClass 來保存水果類型
class FruitClass: Object {
@Persisted var fruitType = ""
}
然后編碼
This is a very memory friendly solution
//get the unique types of fruit. results are lazy!
let results = realm.objects(FruitClass.self).distinct(by: ["fruitType"])
//iterate over the results to get each fruit type, and then filter for those to get the count of each
for fruit in results {
let type = fruit.fruitType
let count = realm.objects(FruitClass.self).filter("fruitType == %@", type).count
print("\(type) has a count of \(count)")
}
和結果
apple has a count of 3
banana has a count of 2
orange has a count of 1
pear has a count of 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.