Swift Firestore 阻止检查字典键是否存在

标签 swift google-cloud-firestore

我有这段代码,它返回 Firestore 查询的结果。因为我想确保这些值存在,所以我正在检查其中的每一个值,例如 if let driverLat = packageDetails["driverLat"] as? Double.. 等 并转换它们。这真的很烦人,我想知道是否有更好的解决方案?

db.collection("packages").document(documentID).getDocument() { (document, error) in
    if let document = document, document.exists {
        if let packageDetails = document.data() as [String: AnyObject]? {
            if let driverLat = packageDetails["driverLat"] as? Double, let driverLon = packageDetails["driverLon"] as? Double {
                if let destinationLat = packageDetails["destinationLat"] as? Double, let destinationLon = packageDetails["destinationLon"] as? Double {
                    // more code
                }
            }
        }
    }
}

最佳答案

我想说您应该使用多个 guard-let 语句。这可以防止金字塔形代码降低可读性。

看起来像这样:

typealias Json = [String: AnyObject]

db.collection("packages").document(documentID).getDocument() { (document, error) in
    guard let document       = document, document.exists else { return }
    guard let packageDetails = document.data() as Json? else { return }

    guard let driverLat      = packageDetails["driverLat"] as? Double else { return }
    guard let driverLon      = packageDetails["driverLon"] as? Double else { return }

    guard let destinationLat = packageDetails["destinationLat"] as? Double else { return }
    guard let destinationLon = packageDetails["destinationLon"] as? Double else { return }

    // more code
}

关于Swift Firestore 阻止检查字典键是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261105/

相关文章:

firebase - 对于事务中的多次写入,Firestore 服务器时间戳是否相同?

swift - SDWebImage 不工作

ios - 无法将 UITableViewCell 设置为单元格

ios - 如何解析单个 JSON 对象数组?

Javascript:无法将对象数组存储到 Firestore

java - 根据不同集合中文档的存在情况将文档添加到集合中

javascript - 如何将当前登录的用户添加为 Firestore 中的字段

iOS Swift 和计时器

string - 如何在 Swift 中创建子字符串?

javascript - 我想将时间戳与当前时间减去一个月进行比较