Eliko Eliko - 2 months ago 15
Swift Question

Cannot call value of non-function type 'Any?!' :- Firebase,Swift3

This is my code before moving to 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)
}
})


This is my code after moving to 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)
}
})


And then I get an error in the 2nd line:


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


The only thing I tried is changing the 2nd line to this code:

snapshot.value as! [String:AnyObject]


But it's not right, there is no "Dogs" included and it's giving me a warning that the
distanceBetweenTwoLocations
code never used.

Answer

See the issue is that when you are instancing and initialising your variable you are telling it that the value its gonna receive will be a value for the object named Dogs present in this snapshot whose type is AnyObject.

But snapshot.value is of type Dictionary i.e [String:AnyObject],NSDictionary..

And the Dogs node that you retrieve is of type, either Dictionary or an Array.

Basically you should avoid to store a value in a variable, of type AnyObject

Try this:-

      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:- Seeing your JSON structure you might wanna convert it into a Dictionary not a Array

Comments