Zhan Zhan - 1 year ago 144
Swift Question

How to get unique value from Realm database in swift

I do news application in

Realm database
. In my database have same news categories. How to get unique value from
Realm database
I use primary key

class News: Object {

dynamic var newsID: String = ""
dynamic var newsTitle: String = ""
dynamic var newsFullText: String = ""
dynamic var newsImage: String = ""
dynamic var newsAutor: String = ""
dynamic var newsCommentCount: String = ""
dynamic var newsSeenCount: String = ""
dynamic var newsDate: String = ""
dynamic var newsCategory: String = ""

override static func primaryKey() -> String? {
return "newsID"

I'm try to get

let realm = try! Realm()
let menuName = realm.objects(News)
for i in menuName.filter("newsCategory") {
nameLabel.text = i.newsCategory

But it is not work.

Answer Source

It is not possible yet to obtain a "distinct"-like functonality from a Realm query (track the open issue here)

However, there are some workarounds suggested in the thread I mentioned above (please read it to get the full context), by user apocolipse :

// Query all users
let allUsers = Realm().objects(User)

// Map out the user types
let allTypes = map(allUsers) { $0.type }

// Fun part: start with empty array [], add in element to reduced array if its not already in, else add empty array
let distinctTypes = reduce(allTypes, []) { $0 + (!contains($0, $1) ? [$1] : [] )

Or better yet, a different approach using Sets (by user jpsim):

let distinctTypes = Set(Realm().objects(User).valueForKey("type") as! [String])

Obviously the workarounds aren't as efficient as a direct DB query, so use with care (and testing under realistic load).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download