Generics and AssociatedTypes

Sorry, I did not have a better title for this, I hope it gets clearer with code.

The idea is to build a simple facade for Persistent Storage of some objects:

class PersistantStorage<T, Codable, Identifiable> {
    func store(_ object: T) throws { }
    
    func objectFor(_ key: T.ID) -> T? {
        return nil
    }
}

As apparent, there is the generic type T, which is constrained to Codable and Identifiable. Now I want to use the later constraint to define my objectFor method, but the compiler complains:

'ID' is not a member type of type 'T'

How would I do this? Or is this completely the wrong approach?

Thanks

Alex

This should work

class PersistantStorage<T: Codable & Identifiable> {
    func store(_ object: T) throws { }
    
    func objectFor(_ key: T.ID) -> T? {
        return nil
    }
}

You could also write it like this:

class PersistantStorage<T> where T: Codable & Identifiable{
    func store(_ object: T) throws { }
    
    func objectFor(_ key: T.ID) -> T? {
        return nil
    }
}

Generics and AssociatedTypes
 
 
Q