本文介绍了swift如何确定变量是否为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道变量是否是可选的
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 }推荐答案
作为一项学术练习(可以做还是应该做),我想出了这一点:
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") }示例:
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))") }输出:
Fred false Optional("Jones") true 37 false Optional(38) true我建议在生产代码中使用它吗?否.我建议尽可能远离Any,我不敢打赌dynamicType的输出保持不变.
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.
更多推荐
swift如何确定变量是否为可选
发布评论