0

I have some Realm Objects that implement Object and Codable protocols. I would like to store them in a struct container that looks like the following:

struct LocalResource<T> where T: Object & Codable {
    init (resource: FileResource) {
        self.realmType = T.self
        self.resource = resource
    }
    
    var codable: [T].Type {
        get {
            [T].self
        }
    }
    var realmType: T.Type
    var resource: FileResource
}

Where I have a generic struct that holds the Realm Model that implements Object and Codable as well as some meta data associated with it. However, when I try to use this struct, such as in the following use:

let localModels: Array<LocalResource<Object & Codable>> = []

I get the error:

'LocalResource' requires that 'Object & Codable' (aka 'RealmSwiftObject & Decodable & Encodable') inherit from 'RealmSwiftObject'

I'm confused because 'Object & Codable' does inherit from RealmSwiftObject. What am I doing wrong?

Tim Ford
  • 5
  • 2
  • 2
    You cannot declare such generic array. You need to provide a concree `LocalResource` type, you cannot mix different `LocalResource` types, since [generic types in Swift are invariant](https://stackoverflow.com/questions/41976844/swift-generic-coercion-misunderstanding). – Dávid Pásztor Dec 02 '21 at 17:20
  • 2
    I think you're going to run into bigger issues down the road as well. Taking lazy Realm objects and storing them in an array makes them not-lazy. That means large datasets will all be loaded into memory and could overwhelm the device - and it will also make things like filtering, sorting etc considerably slower. – Jay Dec 02 '21 at 18:17

0 Answers0