swiftfiltercountrealmrealm-cocoa

How to get the most represented value in Realm?


I have a question regarding Realm on iOS.

I have an object in my Realm DB that looks like this:

class MyObject: Object {
    dynamic var id: Int!
    dynamic var val: String!
}

Let say I populate my table with those data:

| id | val |
|----|-----|
| 1  | A   |
| 2  | B   |
| 3  | A   |
| 4  | B   |
| 5  | A   |
| 6  | A   |

How can query my Realm DB to return the most represented value which is A?

Thanks


Solution

  • Realm doesn't have a native query that'll do exactly that, but you can combine Realm's KVC support with NSCountedSet to get this fairly easily:

    import Foundation
    import RealmSwift
    
    class MyObject: Object {
        dynamic var id: Int = 0
        dynamic var val: String = ""
    }
    
    let realm = try! Realm()
    try! realm.write {
        for (index, value) in ["A", "B", "A", "B", "A", "A"].enumerate() {
            realm.create(MyObject.self, value: [index, value])
        }
    }
    
    let values = realm.objects(MyObject).valueForKey("val") as! [AnyObject]
    let countedSetOfValues = NSCountedSet(array: values)
    let maxElement = countedSetOfValues.allObjects.maxElement { first, second in
        return countedSetOfValues.countForObject(first) < countedSetOfValues.countForObject(second)
    }
    maxElement // => "A"