-2

I want to know if a variable is an optional

I try method below, but fail

func isOptional(v: Any) -> Bool {
    return v is Optional
}
aotian16
  • 767
  • 1
  • 10
  • 21
  • This sounds like an XY problem... I mean... you can tell at compile time... – nhgrif Jul 15 '15 at 12:58
  • possible duplicate of [How to determine if a generic is an optional in Swift?](http://stackoverflow.com/questions/25064644/how-to-determine-if-a-generic-is-an-optional-in-swift) (specifically, `Any` can't be optional, but a generic could be optional) – nhgrif Jul 15 '15 at 13:00
  • @nhgrif thank you for comment. I see this problem too. I am a newbee on swift, it's hard to me. – aotian16 Jul 15 '15 at 13:09

1 Answers1

1

As an academic exercise (can it be done vs. should it be done), I came up with this:

func isOptional(a: Any) -> Bool {
    return "\(a.dynamicType)".hasPrefix("Swift.Optional")
}

Example:

let name = "Fred"
let oname: String? = "Jones"
let age = 37
let oage: Int? = 38

let arr: [Any] = [name, oname, age, oage]

for item in arr {
    println("\(item) \(isOptional(item))")
}

Output:

Fred false
Optional("Jones") true
37 false
Optional(38) true

Would I recommend using this in production code? No. I recommend staying away from Any if at all possible, and I wouldn't bet on the output of dynamicType remaining the same.

vacawama
  • 150,663
  • 30
  • 266
  • 294