swift How to determine if a variable is an optional

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 22:48:46

问题


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
}

回答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.



来源:https://stackoverflow.com/questions/31430962/swift-how-to-determine-if-a-variable-is-an-optional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!