Check if a variable is optional, and what type it wraps

Is it possible to check if a variable is optional, and what type does it wrap?

You can check if a variable is a specific option:

let someString: String? = "oneString" var anyThing: Any = someString anyThing.dynamicType // Swift.Optional<Swift.String> anyThing.dynamicType is Optional<String>.Type // true anyThing.dynamicType is Optional<UIView>.Type // false 

But is it possible to repeat the verification of any type of optional? Something like:

 anyThing.dynamicType is Optional.Type // fails since T cant be inferred // or anyThing.dynamicType is Optional<Any>.Type // false 

And as soon as you find out that you have an option, extract the type that it wraps:

 // hypothetical code anyThing.optionalType // returns String.Type 
+10
swift
Sep 18 '15 at 6:50
source share
2 answers

Since the protocol can be created as a means of the optional Optional , the same protocol can be used to provide access to the optional type. For example, in Swift 2, although it should work similarly in previous versions:

 protocol OptionalProtocol { func wrappedType() -> Any.Type } extension Optional : OptionalProtocol { func wrappedType() -> Any.Type { return Wrapped.self } } let maybeInt: Any = Optional<Int>.Some(12) let maybeString: Any = Optional<String>.Some("maybe") if let optional = maybeInt as? OptionalProtocol { print(optional.wrappedType()) // Int optional.wrappedType() is Int.Type // true } if let optional = maybeString as? OptionalProtocol { print(optional.wrappedType()) // String optional.wrappedType() is String.Type // true } 

The protocol can even be used to validate and deploy an optional value

+6
Sep 25 '15 at 11:27
source share

With Swift2.0:

 let someString: String? = "oneString" var anyThing: Any = someString // is `Optional` Mirror(reflecting: anyThing).displayStyle == .Optional // -> true 

But extracting a wrapped type is not so simple.

You can:

 anyThing.dynamicType // -> Optional<String>.Type (as Any.Type) Mirror(reflecting: anyThing).subjectType // -> Optional<String>.Type (as Any.Type) 

But I don't know how to extract String.Type from Optional<String>.Type wrapped in Any.Type

+5
Sep 18 '15 at 11:12
source share



All Articles