Is it possible to check if a variable is an optional, and what type is it wrapping?
It is possible to check if a variable is an specific optional:
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 check agains 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 once knowing you have an optional, retrieve the type it is wrapping:
// hypothetical code
anyThing.optionalType // returns String.Type
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…