0

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 ?

Cyril
  • 41
  • 1
  • 7
  • 2
    See [Protocol doesn't conform to itself?](https://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself). – Martin R Jun 04 '19 at 08:32
  • `protocol SomeProtocol: DatabaseObject` — is it even legal? – user28434'mstep Jun 04 '19 at 08:44
  • I've seen this question and if I get it right I should try to put `SomeProtocol` in a box and create a struct `AnySomeProtocol` for example. But obviously in this case it won't work as `SomeProtocol` has to inherit from `DatabaseObject`. – Cyril Jun 04 '19 at 08:47

0 Answers0