0

I'm writing some debug code to which I need to pass a parameter of type Any. For printing purposes I'd like to unwrap the parameter value iff it's an optional, but I can't figure out how to test that - every syntactic form I can think of is rejected by the compiler. E.g.,

switch val {
case as Optional<Any>:
    .
    .

and a variety of let forms (including trying .dynamicType) aren't legitimate. Does anyone know how to actually do this? Overall, what I'm trying to accomplish is such that whether or not the value is an optional, I get the actual value into a string and not Optional.

Amira
  • 23
  • 1
  • 3
Feldur
  • 1,121
  • 9
  • 23

1 Answers1

1

Martin is absolutely correct. From the linked post, modified slightly because I wanted a different return for nil:

func unwrap(any:Any, ifNil: Any = "nil") -> Any {

    let mi = Mirror(reflecting: any)
    if mi.displayStyle != .Optional {
        return any
    }

    if mi.children.count == 0 { return ifNil }
    let (_, some) = mi.children.first!
    return some

}
Feldur
  • 1,121
  • 9
  • 23