无法调用非function类型的值’任何?!’ : – Firebase,Swift3

转到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) } }) 

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

无法调用非function类型的值’任何?!’

我尝试过的唯一一件就是将第二行更改为此代码:

 snapshot.value as! [String:AnyObject] 

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

看到的问题是,当您实例化并初始化变量时,您告诉它它将接收的value将是此快照中名为Dogs的对象的value ,其类型为AnyObject

但是snapshot.value的类型为Dictionary ie [String:AnyObject]NSDictionary ..

您检索的Dogs节点的类型是Dictionary或Array。

基本上,您应该避免将值存储在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结构你可能想把它转换成字典而不是数组

在Swift 3中, AnyObject已经改为Any ,它实际上可以是任何东西。 特别是当使用键和索引下标时,现在需要告诉编译器实际类型。

解决方案是将snapshot.value为Swift字典类型[String:Any] 。 可选绑定安全地展开值

 if let snapshotValue = snapshot.value as? [String:Any], let currentData = snapshotValue["Dogs"] as? [String:Any] { let mylat = currentData["latitude"] as! [String] ... 

你使用了太多惊叹号。 之前不需要latitude"]之后的标记as!并且if let而不是检查nil if let始终使用。

我还有一个代码,允许您访问子节点的值。 我希望这可以帮助你:

 if let snapDict = snapShot.value as? [String:AnyObject] { for child in snapDict{ if let name = child.value as? [String:AnyObject]{ var _name = name["locationName"] print(_name) } } } 

此致,Nazar Medeiros