How to get unique values ​​from Realm to Swift? I have a class and the newsCategory property has duplicate values

 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 need to get from the database unique news categories from newsCategory .

Tried so

 let realm = try! Realm() let news = realm.objects(News) let filter = news.filter("newsCategory") 

Does not work.

    1 answer 1

    That's decided

     extension Results { func uniqueValueForObject<U : Equatable>(objectKey: String, paramKey: String, type: U.Type)->[U]{ var uniqueValues : [U] = [U]() for obj in self { if let o = obj.valueForKeyPath(objectKey) { if let v = o.valueForKeyPath(paramKey){ if(!uniqueValues.contains(v as! U)){ uniqueValues.append(v as! U) } } } } return uniqueValues } func uniqueValue<U : Equatable>(paramKey: String, type: U.Type)->[U]{ var uniqueValues : [U] = [U]() for obj in self { if let val = obj.valueForKeyPath(paramKey) { if (!uniqueValues.contains(val as! U)) { uniqueValues.append(val as! U) } } } return uniqueValues } func uniqueObject(paramKey: String)->[Object]{ var uniqueObjects : [Object] = [Object]() for obj in self { if let val = obj.valueForKeyPath(paramKey) { let uniqueObj : Object = val as! Object if !uniqueObjects.contains(uniqueObj) { uniqueObjects.append(uniqueObj) } } } return uniqueObjects } } 

    Then we use

     let unique1 = try! Realm().objects(News).uniqueValue("name", type: String.self) let unique2 = try! Realm().objects(News).uniqueValueForObject("subItem", paramKey: "name", type: String.self) let unique3 = try! Realm().objects(News).uniqueObject("subItem")