Search code examples
iosswiftrealm

How to make universal GET method for Realm objects?


I my viewControllers I often use realm.objects(className.self) to download data from className table. I wanted to simplify that so I created another swift file with get method.
It looks like this:

class Realm_manager {
    private init() {}
    static let shared = Realm_manager()

    let realm = try! Realm()
    func getObjects() -> [customType]{
            let result = realm.objects(customType.self)
            return Array(result)
        } 
}

But that getObjects method works only for customType objects. With this in viewController it works fine:

    let result = Realm_manager.shared.getObjects()
    for item in result {
            myArray.append(item)
        }
    //this works because myArray is of type customType.

I want to make getObjects universal method which can accept any class.


Solution

  • Use Generics

    class RealmManager {
        private init() {}
        static let shared = RealmManager()
    
        let realm = try! Realm()
    
        func getObjects<T: Object>() -> [T] {
            let result = realm.objects(T.self)
            return Array(result)
        } 
    }
    

    usage:

    let manager = RealmManager.shared
    let dogs: [Dogs] = manager.getObjects()
    

    Note: In Swift we generally do not use underscores in Type names, they are normally upper camel cased. Realm_manager -> RealmManager