Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.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
iOS Firebase从子节点检索数据始终为零_Ios_Swift_Firebase_Firebase Realtime Database - Fatal编程技术网

iOS Firebase从子节点检索数据始终为零

iOS Firebase从子节点检索数据始终为零,ios,swift,firebase,firebase-realtime-database,Ios,Swift,Firebase,Firebase Realtime Database,我正在尝试读取纬度和经度数据,该数据存储在随机子ID下。我的数据结构如下: 这是我的检索代码 ref.child("locations").observe(.value, with: { snapshot in for child in snapshot.children { let valueD = child as! DataSnapshot let randomkey = valueD.key

我正在尝试读取纬度和经度数据,该数据存储在随机子ID下。我的数据结构如下:

这是我的检索代码

ref.child("locations").observe(.value, with: { snapshot in
for child in snapshot.children  {
                let valueD = child as! DataSnapshot
                let randomkey = valueD.key
                print(randomkey)
                print(valueD.value)
                let lat = (valueD.value as? NSDictionary)?["Latitude"] as? String
                print(lat) 
}})
对于
valueD.value
,控制台将打印此值(正确)

但是,对于
lat
,它返回
nil


为什么
lat
没有值?我怎样才能解决这个问题?谢谢

如果让lat=child.value[“Latitude”]as,您是否尝试过使用
?双重的
?例如:

ref.child("locations").observe(.value, with: { snapshot in
for child in snapshot.children  {

                let valueD = child as! DataSnapshot
                let randomkey = valueD.key
                print(randomkey)
                print(valueD.value)

                if let lat = child.value["Latitude"] as? Double {
                    print(lat)
                }
}})

您必须安全地打开可选包装。有很多方法可以做到这一点。我最喜欢的方法之一是使用
guard let
语句

// This output already says 'Optional'
Optional({
Latitude = "1.342433333333333";
Longitude = "103.9639883333333";
Type = 0;
})
像这样打开它:

ref.child("locations").observe(.value, with: { snapshot in
for child in snapshot.children  {

                let valueD = child as! DataSnapshot
                let randomkey = valueD.key
                print(randomkey)
                print(valueD.value)

                // Unwrap
                guard let childValue = valueD.value else { return }
                print(childValue["Latitude"])
}})

谢谢大家的回复!这确实是关于展开可选文件的问题

我尝试了以前的解决方案。这个解决方案最适合我,因为我从数据库中知道我肯定会有经纬度数据:交换为感叹号

let latitude = (valueD.value as! NSDictionary)["Latitude"] as! Double

首先,请尝试打印此文件(valueD.value为?NSDictionary)。检查是否有字典输出。啊,太好了!看起来像是代码中的字符串,但实际上可能是截图中的两倍!很高兴你发现了!
let latitude = (valueD.value as! NSDictionary)["Latitude"] as! Double