1

In a generic function, I want to test if a given object conforming to a certain protocol is of a given type. It works great if a concrete class type is passed as a parameter to the checking function. However, when I use a variable for the type (using ternary operator), I get an error:

Cannot invoke 'isObject' with an argument list of type '(AnyObject, of: P.Type)'

Casting additionally the type variable to P.Protocol doesn't help either, since:

In argument type 'P.Protocol', 'P' does not conform to expected type 'P'

protocol P {
    static var descr: String {get}
}

class A: P {
    static let descr = "class A"
}

class B: P {
    static let descr = "class B"
}

class Test {
    func isObject<T:P>(_ object: AnyObject, of type: T.Type) -> Bool {
        print("descr: \(type.descr)")
        return object is T
    }
}

let a = A()
let type = (false ? A.self : B.self) as P.Type //as! P.Protocol
let test = Test()

test.isObject(a, of: type)
Hamish
  • 78,605
  • 19
  • 187
  • 280
VKharion
  • 11
  • 1

1 Answers1

0

The problem is that with a generic placeholder T, when T is a protocol type P, T.Type is P.Protocol not P.Type. In other words, it takes a metatype that describes the protocol itself rather than a metatype that describes a type that conforms to the protocol. This distinction is important because protocols don't conform to themselves.

One solution in your case is to introduce a wrapper around a P.Type metatype which uses a generic placeholder in the initialiser in order to store a closure to perform the is check for you.

struct AnyPType {

    let base: P.Type
    private let _isInstance: (Any) -> Bool

    /// Creates a new AnyType wrapper from a given metatype.
    /// The passed metatype's value **must** match its static value, i.e `T.self == base`.
    init<T : P>(_ base: T.Type) {
        precondition(T.self == base, "The static value \(T.self) and dynamic value \(base) of the passed metatype do not match")
        self.base = T.self
        self._isInstance = { $0 is T }
    }

    func isInstance(_ instance: Any) -> Bool {
        return _isInstance(instance)
    }
}

This is a specialised version of the wrapper that I show in my answer to this Q&A, in which I also show how to lift the limitation of T.self == base on Apple platforms (but this limitation shouldn't be a problem in your case).

You can now use the wrapper like so:

class Test {
    func isObject(_ object: Any, of type: AnyPType) -> Bool {
        print("descr: \(type.base.descr)")
        return type.isInstance(object)
    }
}

let type = AnyPType(A.self) // or AnyPType(B.self)

print(Test().isObject(A(), of: type))

// descr: class A
// true
Hamish
  • 78,605
  • 19
  • 187
  • 280