我有这段代码,它返回 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/