0

I have the following situation: (just copy it into a playground)

import Cocoa

protocol UID {
    var uid: Int {get set}
}

class A : UID {
    var uid = 01
}

class manageUID<T: UID> {

    let cache = NSCache()

    func addUID(aObj: T) {
        cache.setObject(aObj, forKey:aObj.uid)
    }

    func deletedUID(aObj: T) {
        cache.removeObjectForKey(aObj.uid)
    }
}

This lead to the error "Could not find an overload for setObject ..."

Well i know the problem is the type of aObj in addUID, it is not clear for the compiler.

On way would be to say

func addUID(aObj: T) {
    cache.setObject(aObj as A, forKey:aObj.uid)
}

But in this case a can skip the generic topic completely. I try to downcast the aObj to something like AnyObject or NSObject but it did not work.

Any ideas?

I would be nice to have a generic version of a cache :)

UPDATE:

On solution is to add the @objc attribute on the protocol, therefore the protocol is only usable for classes but this lead to the general restriction for the protocol. I just like a local solution in the class manageUID.

Stephan
  • 4,263
  • 2
  • 24
  • 33

1 Answers1

0

I found another solution, primary derived from the answer of my question here: https://devforums.apple.com/thread/233432

 protocol UID {
    var uid: Int {get set}
 }

 @class_protocol
 protocol ObjectUID : UID {

 }


 class manageUID<T: ObjectUID> {

    let cache = NSCache()

    func addUID(aObj: T) {
        cache.setObject(aObj, forKey:aObj.uid)
    }

    func deletedUID(aObj: T) {
        cache.removeObjectForKey(aObj.uid)
    }
 }
Stephan
  • 4,263
  • 2
  • 24
  • 33