0

In my app I'm using a CRUD class that enables me to do database operations with generics. The createfunction looks like this:

func create<T: Storable>(_ object: T.Type, completion: ((T) -> ())?)

This allows me to do the following:

database.create(Restaurant.self, completion: nil)

Now, the Storable protocol has a property called primaryKey. However, when I try to access that inside the create function, it always passes me the default.

protocol Storable {

}
extension Storable {
    static var primaryKey: String {
        get {
            return "Storable"
        }
    }
}

class Restaurant: Storable {
    override public class var primaryKey: String {
        return "uuid"
    }
}

...

class Database {
    public func create<T: Storable>(_ object: T.Type, completion: ((T) -> ())?) {
        print("Primary key: ", object.primaryKey)
        print("T: ", type(of: T.init()))
    }
 }

The above will print the following:

Primary key: Storable
T:  Storable

Obviously, the primary key should be "uuid". What am I doing wrong?

user4992124
  • 1,574
  • 1
  • 17
  • 35
  • 1
    Duplicate of https://stackoverflow.com/questions/31431753/swift-protocol-extensions-overriding – matt Aug 07 '19 at 13:02

1 Answers1

4

Add your property as a requirement in the protocol declaration.

protocol Storable {
    static var primaryKey: String {get}
}
extension Storable {
    static var primaryKey: String {
        get {
            return "Storable"
        }
    }
}

Otherwise you have no polymorphism (as you’ve observed).

matt
  • 515,959
  • 87
  • 875
  • 1,141