如何检查 属性 是否已强制向下转型

How to check nil for a property already forcefully downcasts

我有一个简单的问题,但找不到合适的解决方案。我有一个看起来像这样的 swift 代码。

 let id  = dic["id"] as! String

我需要检查 dic["id"] 是否为零。我可以像这样检查 nil

if let safeId = dic["id"]{
   let id = safeId as! String
}

但问题是我有许多值要解包,对每个 属性 执行上述步骤似乎不切实际。我想要像下面这样的东西,但它不起作用,因为向下转换总是 returns 一个值,所以它不是可选的,因此不能展开。

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 */
             }

将所有 ! 替换为 ?if let 展开 optionals

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 */
   }

你的我可以检查 nil 的例子也是不好的做法。应该是

if let safeId = dic["id"] as? String {
   let id = safeId
}

请阅读(Optionals in) the Language Guide

部分