[Solved] swift How to determine if a variable is an optional


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.

0

solved swift How to determine if a variable is an optional