0

Ok, I have made this protocol to cover object caching with the help of Realm. In protocol I define cache: Object? which type is defined by Realm library.

protocol PersistantCaching {
  var cache: Object?   { get set }
}

Then I use this protocol in class ClientDetails it works.

class Client: PersistantCaching {
  var cache: Object?
}

But Object is too general. So in my case I create Object subclass

class LocalClient: Object {
  dynamic var name = ""
}

And now if I change class Client to support LocalClient like this

class Client: PersistantCaching {
  var cache: LocalClient?
}

I get an error, that Type 'Client' does not conform to protocol 'PersistantCaching'

How to write generic protocol that define a variable which also accepts subclass of specified Type?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Klemen
  • 2,144
  • 2
  • 23
  • 31
  • 1
    You can't – at least not the way you're currently trying to do it – your `PersistantCaching` protocol says that you can assign *any* optional `Object` instance to the property `cache`. `Client` says you can only assign an optional `LocalClient` instance – which contradicts with the protocol. Compare [Swift Protocol inheritance and protocol conformance issue](http://stackoverflow.com/q/40410884/2976878). – Hamish Apr 10 '17 at 13:39
  • Ok, if it can't be done, that do you have any suggestion how to do this some other way. So to leave the protocol as it is. And rather prepare other classes to be constructed to also work with subclasses of Object type. – Klemen Apr 10 '17 at 13:52

1 Answers1

2

Use an associatedtype:

protocol PersistantCaching {
    associatedtype CacheObject: Object
    var cache: CacheObject?   { get set }
}

(I'm assuming here that you want the cache always to be a subclass of Object.)

Rob Napier
  • 286,113
  • 34
  • 456
  • 610