Parse query does not return on first attempt - Swift

I have a segment control that determines what is loaded into the table view. I load the table for index 0 in viewDidLoad and it works fine. The segment control is ‘selected’ to index 0 via storyboard. When the index is switched to index 1 I get the alert message I set “No items owned”, it will print an empty array and it has me stay at index 0. When I click index 1 for the second time, it finds the items and loads the table I want for index 1 and it prints all the objects. Why does the query for getOwnedCosmetics not return anything the first time the segment is changed to index 1?

@objc func getOwnedCosmetics (cosmetic : String){
        if PFUser.current() != nil {
        let query = PFQuery(className: (cosmetic + owned))
        query.whereKey("theUser", equalTo: PFUser.current()?.objectId as Any)
        query.findObjectsInBackground(block: { (objects, error) in
            if error != nil {
                print(error)
            } else if let objects = objects {
            self.cosmeticIdOwned.removeAll()
                for object in objects {
                        self.cosmeticIdOwned.append(object["theCosmetic"] as! String)
                }
            }
        })
            print (cosmeticIdOwned)
            if cosmeticIdOwned.count > 0 {
        getOwnedCosmeticsQuery()
            }
            else {
                self.displayAlert(title: "No items owned", message: "Add \(cosmeticTracker) to your collection")

                seg.selectedSegmentIndex = 0
            }
        }
        else {
             self.displayAlert(title: "Unable to retrieve data", message: "Please sign in")
            seg.selectedSegmentIndex = 0
        }
    }

I would like to note if I populate cosmeticIdOwned with an item in viewDidLoad. It will make it to getOwnedCosmeticsQuery and find the item, even though it is not actually ‘owned’. When I click the segment for getOwnedCosmetics for the second time, it runs getOwnedCosmeticsQuery with the correct objects it found from getOwnedCosmetics.

Hi @amd6y6,

Thanks for being part of the GitHub Community Forum! We’re glad you’re here.

I wanted to jump in here, and mention that if you don’t get the help you’re looking for from this particular community, you might want to try getting help somewhere that focuses on Swift. It’s definitely possible another GitHub user might have run into this same issue and can help, but the GitHub Community Forum focuses primarily on topics related to GitHub itself or collaboration on project development and ideas. We want to make sure you’re getting the best support you can, but this forum may not be the right place for this particular topic.

Best of luck!