ios - 如何检查 nil 是否已经强制向下转换的属性
问题描述
我有一个简单的问题,但找不到合适的解决方案。我有一个看起来像这样的快速代码。
let id = dic["id"] as! String
我需要检查dic["id"]是否为零。我可以像这样检查 nil
if let safeId = dic["id"]{
let id = safeId as! String
}
但问题是我有许多值要解包,对每个属性执行上述步骤似乎不切实际。我想要类似下面的东西,但它不起作用,因为向下转换总是返回一个值,所以它不是可选的,因此不能解包。
if let snap = child as! DataSnapshot,
let dic = snap.value as! [String : Any],
let firstName = dic["first_name"] as! String,
let lastName = dic["last_name"] as! String,
let image = dic["user_image"] as! String,
let id = dic["id"] as! String{
/* My code */
}
此方法给出了一个错误,称为Initializer for conditional binding must have Optional type, not 'String' 我不是高级开发人员,请帮我解决这个问题。
解决方案
!
用?
,替换if let
所有选项
if let snap = child as? DataSnapshot,
let dic = snap.value as? [String : Any],
let firstName = dic["first_name"] as? String,
let lastName = dic["last_name"] as? String,
let image = dic["user_image"] as? String,
let id = dic["id"] as? String{
/* My code */
}
您的I can check for nil example 也是不好的做法。它应该是
if let safeId = dic["id"] as? String {
let id = safeId
}
推荐阅读
- asp.net-core - 如何在 ASP.NET Core MVC 中设置会话超时/到期时间?
- sql - postgresql 11.6 中的临时表创建问题
- sparql - 使用 concat 查询到第二和第三级的 SPARQL
- c# - Automapper 成员的自定义配置仅支持类型上的顶级个人成员
- mysql - sql中的对称对
- python - 使用 boto3 获取 elasticloadbalancers 名称
- google-chrome - 在 chrome 的内容脚本中下载 chrome.downloads.download 函数中的文件时如何发送 cookie?
- ruby-on-rails - 如何使用carrierwave上传多个文件并创建多个记录
- wordpress - 从类别名称生成的父类别和子类别默认文本
- angular - 添加@angular/pwa 包时出错:规则结果无效:Promise 类的实例。这是我为 7.1.4 角度版本解决它的方法