Determine if Any.Type is Optional

Im trying to determine if a given type t ( Any.Type ) is an optional type, Im uses this test

 t is Optional<Any>.Type 

but it always returns false.

So, is there a way to achieve this?

+8
dynamic swift
Sep 12 '15 at 7:39 on
source share
3 answers

Assuming you are trying to do something like this:

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

Unfortunately, currently (with Swift 2) covariance or contravariance is not supported, and type checks directly against Optional.Type cannot be performed:

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

An alternative is to create an Optional extension to a specific protocol and check for this type:

 protocol OptionalProtocol {} extension Optional : OptionalProtocol {} let anyType: Any.Type = Optional<String>.self anyType is OptionalProtocol.Type // true 
+7
Sep 25 '15 at 6:56
source share

A bit late for the party. But I ran into the same problem. Here is my code.

 func isOptional(_ instance: Any) -> Bool { let mirror = Mirror(reflecting: instance) let style = mirror.displayStyle return style == .optional } let a: Int = 1 // false let b: Int? = 2 // true let c: Double = 3.0 // false let d: Double? = 4.0 // true let e: NSString = "Hello" // false let f: NSString? = "Hello" // true isOptional(a) // fasle isOptional(b) // true - warning isOptional(c) // false isOptional(d) // true - warning isOptional(e) // false isOptional(f) // true - warning 

It looks good to me. swift4

+1
Feb 08 '18 at 17:00
source share

To achieve this, you can use generics:

 func isOptional<T>(x:T?)->Bool { return true } func isOptional<T>(x:T)->Bool { return false } 

Edit

The above code can be used to find out if a variable is an optional type. The only way to find out about a variable containing a type is to use reflection:

 var t1:Any.Type=(String?).self var t2:Any.Type=(String).self Mirror(reflecting: t1).description Mirror(reflecting: t2).description 

The first call to Mirror gives the string "Mirror for Optional<String>.Type" and the second gives "Mirror for String.Type" .

I understand that string comparison is not a convenient way to do this check, I will try to find something more perfect again.

-2
Sep 15 '15 at 16:13
source share



All Articles