swift如何确定变量是否为可选

编程入门 行业动态 更新时间:2024-10-20 13:39:18
本文介绍了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如何确定变量是否为可选

本文发布于:2023-11-29 17:15:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   变量   swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!