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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…