Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift Firestore防止检查字典密钥是否存在_Swift_Google Cloud Firestore - Fatal编程技术网

Swift 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

我有一段代码,它返回Firestore查询的结果。因为我想确保这些值存在,所以我要检查它们中的每一个,比如
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
}