Hi everyone,
I have trouble finding the right model to design a class that has a parent-children relationship with another class. Both classes are generic and are intended to be subclassed.
This summary might not be very clear so let's start with a simple example : a database that holds a reference to all its objects and each object hold a weak reference to its database.
class Database {
var objects: [DatabaseObject] {
didSet {
for object in objects {
object.database = self
}
}
}
}
class DatabaseObject {
weak var database: Database?
}
Now in my app my goal is to define a subclass of Database
and subclasses of DatabaseObject
for every kind of object I need to deal with. Obviously I can start with something like that :
class MyAppDatabase: Database {
}
class SomeDatabaseObject: DatabaseObject {
}
let object = SomeDatabaseObject()
But problem is object.database
returns a Database
whereas it would be nice to return a MyAppDatabase
. So let's get generic and change things a bit :
class DatabaseObject<D: Database> {
weak var database: D?
}
class SomeDatabaseObject: DatabaseObject<MyAppDatabase> {
}
With that change object.database
would return a MyAppDatabase
as I want but the question is, how to define the Database
class accordingly ? Something like that comes to mind but it doesn't compile.
class Database<O: DatabaseObject<Self>> {
var objects: [O] {
didSet {
for object in objects {
object.database = self
}
}
}
}
So what would be the correct to way to design this ? Thanks for your advice.