Swift Firestore防止检查字典密钥是否存在
我有一段代码,它返回Firestore查询的结果。因为我想确保这些值存在,所以我要检查它们中的每一个,比如Swift Firestore防止检查字典密钥是否存在,swift,google-cloud-firestore,Swift,Google Cloud Firestore,我有一段代码,它返回Firestore查询的结果。因为我想确保这些值存在,所以我要检查它们中的每一个,比如if let driverLat=packageDetails[“driverLat”]as?双重的etc,也可以铸造它们。这真的很烦人,我想知道是否有更好的解决办法 db.collection("packages").document(documentID).getDocument() { (document, error) in if let document = documen
if let driverLat=packageDetails[“driverLat”]as?双重的etc
,也可以铸造它们。这真的很烦人,我想知道是否有更好的解决办法
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
}