SoundShock SoundShock - 1 year ago 494
Swift Question

Filtering Realm objects with Swift

I always get the following error when trying to filter my Realm database using


Property 'text' is not a link in object of type 'getType'

I want to filter my Realm database to show only the items that have some specific text in them. This is what I've tried:

let realm = try! Realm()
let predicate = NSPredicate(format: "typez.text.filter = 'special'")
let filterThis = realm.objects(Publication).filter(predicate)

The relevant portion of my model classes is:

class Publication: Object, Mappable {
dynamic var id: Int = 0
var typez = List<getType>()
dynamic var url: String?

class getType: Object, Mappable {
dynamic var text: String = ""

Answer Source

I don't usually use NSPredicate's directly, instead I do an inline predicate closure within the filter paramter.

let realm = try! Realm()
                     //Array of publications             
    let realmObjects = realm.objects(Publication)
    //any publication where .text property == special will be filtered. and filter out empty array
    let filterThis = realmObjects.filter({ $0.getType.filter({ $0.text == "special" } != [] ) })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download