这是我的代码before迁移到 Swift 3:
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
let currentData = snapshot.value!.objectForKey("Dogs")
if currentData != nil {
let mylat = (currentData!["latitude"])! as! [String]
let mylat2 = Double((mylat[0]))
let mylon = (currentData!["longitude"])! as! [String]
let mylon2 = Double((mylon[0]))
let userid = (currentData!["User"])! as! [String]
let userid2 = userid[0]
let otherloc = CLLocation(latitude: mylat2!, longitude: mylon2!)
self.distanceBetweenTwoLocations(self.currentLocation, destination: otherloc, userid: userid2)
}
})
这是我的代码after迁移到 Swift 3:
ref.observe(.childAdded, with: { snapshot in
let currentData = (snapshot.value! as AnyObject).object("Dogs")
if currentData != nil {
let mylat = (currentData!["latitude"])! as! [String]
let mylat2 = Double((mylat[0]))
let mylon = (currentData!["longitude"])! as! [String]
let mylon2 = Double((mylon[0]))
let userid = (currentData!["User"])! as! [String]
let userid2 = userid[0]
let otherloc = CLLocation(latitude: mylat2!, longitude: mylon2!)
self.distanceBetweenTwoLocations(self.currentLocation, destination: otherloc, userid: userid2)
}
})
然后我在第二行收到错误:
无法调用非函数类型“Any?!”的值
我唯一尝试的是将第二行更改为以下代码:
snapshot.value as! [String:AnyObject]
但这是不对的,其中没有“狗”,它给了我一个警告:distanceBetweenTwoLocations
代码从未使用过。
看到的问题是,当您是实例并初始化变量时,您告诉它它将收到的值将是value
对于名为Dogs
存在于该快照中,其类型为AnyObject
.
But snapshot.value
是字典类型,即[String:AnyObject]
,NSDictionary
..
And the Dogs
您检索的节点的类型为“字典”或“数组”。
基本上,您应该避免将值存储在 AnyObject 类型的变量中
尝试这个:-
FIRDatabase.database().reference().child("Posts").child("post1").observe(.childAdded, with: { snapshot in
if let currentData = (snapshot.value! as! NSDictionary).object(forKey: "Dogs") as? [String:AnyObject]{
let mylat = (currentData["latitude"])! as! [String]
let mylat2 = Double((mylat[0]))
let mylon = (currentData["longitude"])! as! [String]
let mylon2 = Double((mylon[0]))
let userid = (currentData["User"])! as! [String]
let userid2 = userid[0]
let otherloc = CLLocation(latitude: mylat2!, longitude: mylon2!)
self.distanceBetweenTwoLocations(self.currentLocation, destination: otherloc, userid: userid2)
}
})
PS:-看到 JSON 结构,您可能想将其转换为字典而不是数组
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)