Is it possible to provide confirming protocol in generic functions of another protocol? I tried make it work like this, but it's impossible, or I made some mistakes.
My code:
protocol DataModelProtocol {
associatedtype ObjectProtocol: Protocol
func fetchObjects<T: ObjectProtocol>() -> [T]?
func fetch<T: ObjectProtocol>(object: T) -> T?
func delete<T: ObjectProtocol>(allObjectOf type: T.Type)
func insert<T: ObjectProtocol>(_ object: T)
func save<T: ObjectProtocol>(_ object: T)
func update<T: ObjectProtocol>(_ object: T)
func delete<T: ObjectProtocol>(_ object: T)
}
Error message:
inheritance from non-protocol, non-class type 'Self.ObjectProtocol'
It works only like this, but I want to make it more flexible:
protocol DataModelProtocol {
typealias ObjectProtocol = NSManagedObject
...
}
This would perhaps be easier is you gave responsibility of the return types to the object classes themselves.
You would need two protocols but it would avoid mixing protocols and generics:
... Here is a simple (naive) example of how the protocols can be used. (I intentionally chose not to use core data to illustrate the generality of the solution) ...
... Using the protocols will be a bit different from your approach because you would be starting from the object classes rather than passing them as parameter to the model ...