I have an app which saves its data in a database and as I rewrite it entirely in Swift I'm facing the following problem.
Basically I have a root class DatabaseObject
which all objects in the database inherit from. Then at some point I want to declare a protocol that some database objects will adopt. Finally I would like to be able to use that protocol in generic functions but it won't compile.
Here is a simplified code that you can run in a playground :
class DatabaseObject {
var id: String
init(id: String) {
self.id = id
}
}
protocol SomeProtocol: DatabaseObject {
func someFunc()
}
func getObject<T: DatabaseObject>(id: String, type: T.Type) -> T? {
// Fetch the object and returns it
// [...]
return nil
}
let object1 = getObject(id: "XXX", type: DatabaseObject.self)
let object2 = getObject(id: "XXX", type: SomeProtocol.self)
Last line generates the error "Cannot convert value of type 'SomeProtocol.Protocol' to expected argument type 'DatabaseObject.Type'".
SomeProtocol
inherits from DatabaseObject
so I would expect this code to work.
As a workaround I can do that :
let workaround = getObject(id: "XXX", type: DatabaseObject.self) as? SomeProtocol
but I don't like it as it kind of defeats the purpose of making a generic function…
Is this a Swift limitation ? Does anyone have a better idea ?