swiftdynamic

Determine if Any.Type is Optional


I’m trying to determine if a given type t (Any.Type) is an optional type, I’m using this test

t is Optional<Any>.Type

but it returns always false.

So is there any way to achieve this?


Solution

  • Assuming that what you are trying to do is something like this:

    let anyType: Any.Type = Optional<String>.self
    anyType is Optional<Any>.Type // false
    

    Sadly swift currently (as of Swift 2) does not support covariance nor contravariance and type checks directly against Optional.Type cannot be done:

    // Argument for generic parameter 'Wrapped' could not be inferred
    anyType is Optional.Type // Causes error
    

    An alternative is to make Optional extend an specific protocol, and check for that type:

    protocol OptionalProtocol {}
    
    extension Optional : OptionalProtocol {}
    
    let anyType: Any.Type = Optional<String>.self
    anyType is OptionalProtocol.Type // true