We're finding that our project has lots of duplicated/boilerplate code surrounding collections of realm objects for basic list view controllers, and wondering if there's some generic container we can encapsulate them in.
It seems like AnyRealmCollection
is vaguely related to that concept, and I found this old/spuriously sourced link and this stackoverflow post in which it does basically exactly what I want, but that syntax definitely doesn't work anymore. My goal is basically the following (pardon my pseudocode)
class ParentController: UITableViewController {
var dataSource: GenericRealmCollection!
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
}
class ChildController: ParentController {
func viewDidLoad() {
dataSource = realm.objects(MyModel.self).filter(...)
}
}
I'm guessing there's some swift type-erasure thing that i'm not fully understanding that will accommodate this, but I've been playing around with it most of the afternoon and haven't made much progress.
Update 1
Looks like AnyRealmCollection
definitely isn't what i'm looking forward based on @kishikawa-katsumi's explanation. As I mentioned in the comments, doing that forces class generics, which really limit interoperability with Obj-C. My hope is to completely erase the type (or at least get back to Object
, then have helper functions for casting to the right type when I need the objects. It's looking like this may not be possible.