首页 > 解决方案 > 如何检查 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' 我不是高级开发人员,请帮我解决这个问题。

标签: iosswiftoptional

解决方案


!?,替换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
}

请阅读(选项中的部分)语言指南


推荐阅读