gpt4 book ai didi

ios - 无法调用非函数类型的值 'Any?!' :- Firebase, Swift3

转载 作者:搜寻专家 更新时间:2023-11-01 05:50:15 25 4
gpt4 key购买 nike

这是我迁移到 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)
}
})

这是我迁移到 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)
}
})

然后我在第二行收到一个错误:

Cannot call value of non-function type 'Any?!'

我唯一尝试的是将第二行更改为以下代码:

snapshot.value as! [String:AnyObject]

但这不对,没有包含“Dogs”,它警告我从未使用过 distanceBetweenTwoLocations 代码。

最佳答案

看到的问题是,当您实例化和初始化您的变量时,您告诉它它将接收的值将是一个 value 对于名为 Dogs 的对象出现在这个类型为 AnyObject 的快照中.

但是 snapshot.value 是字典类型,即 [String:AnyObject] , NSDictionary ..

还有 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 结构,您可能想将其转换为字典而不是数组

关于ios - 无法调用非函数类型的值 'Any?!' :- Firebase, Swift3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com