0

I am saving a parse query to a array but i ket the following error on if let objects = objects as? [PFObject]

And the following error happens Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals.

any one know how to solve this?

func getArray(funcstring: String){
        
        var userGeoPoint: PFGeoPoint
        PFGeoPoint.geoPointForCurrentLocationInBackground {
            (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
            if error == nil {
        
            userGeoPoint = geoPoint!
            }
        }
        
        
        var searchQuery: [String] = [String]()
        
        var query = PFQuery(className:"User")
        query.whereKey("geoLocation", nearGeoPoint:userGeoPoint)
        query.limit = 100
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in
            if error == nil {
                if let objects = objects as? [PFObject] {
                    for object in objects {
                        self.searchQuery.append(object.objectForKey("objectId") as! String)
                        
                    }
                    
                }
            } else {
                print("\(error?.userInfo)")
            }
        }

        
        
        
        
                }
user4174219
  • 427
  • 5
  • 13

1 Answers1

0

objects is declared as [PFObject]?.

You're going to downcast the object to something the compiler already knows.

Just check for nil

if let unwrappedObjects = objects {
  for object in unwrappedObjects {
     self.searchQuery.append(object.objectForKey("objectId") as! String)    
  }
}

or still "swiftier"

if let unwrappedObjects = objects {
   self.searchQuery = unwrappedObjects.map{ $0["objectId"] as! String }   
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Hi Thanks for your response it worked but now i get the following error as self.searchQuery.append.... , Value of type "viewcontroller " has no member 'searchQuery' – user4174219 Nov 28 '15 at 17:09
  • `searchQuery ` is supposed to be declared on class scope (as instance variable) rather than in the `getArray()` method or if it's really meant as a local variable omit `self` – vadian Nov 28 '15 at 17:16
  • Sorry im new to coding where abouts should i declare it – user4174219 Nov 28 '15 at 17:18
  • Class scope means within the top braces `class viewController : UIViewController { var ... }` – vadian Nov 28 '15 at 17:20