Caleb L
Caleb L

Reputation: 139

Parse.com Query with swift 1.2 and string array

I am trying to query from parse.com and I would db receiving about 100 objects per time. I used the swift example code on their website, and the app doesn't build with that code. So I looked around and found that people were using code similar to this:

 var query = PFQuery(className:"posts")
    query.whereKey("post", equalTo: "true")
    query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
        // do something


        self.myDataArray = objects as! [String]

    })

This does not work, because I am trying to convert PFObject to String

I would need to get the one one value from each object into a swift string array [String]. How do I get just the one text value, instead of the PFObject and how do I get it into the swift string array?

Upvotes: 0

Views: 719

Answers (2)

Daniel Rushton
Daniel Rushton

Reputation: 578

For starters, I would definitely recommend using the "if let" pattern to qualify your incoming data. This is a nice Swift feature that will help avoid run-time errors.

var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock(
{ (objects: [AnyObject]?, error: NSError?) -> Void in

    // check your incoming data and try to cast to array of "posts" objects.
    if let foundPosts = objects as? [posts]
    {   
        // iterate over posts and try to extract the attribute you're after
        for post in foundPosts
        {   
            // this won't crash if the value is nil
            if let foundString = post.objectForKey("keyForStringYouWant") as? String
            {
                // found a good data value and was able to cast to string, add it to your array!
                self.myDataArray.addObject(foundString)
            }
        }
})

Upvotes: 0

danh
danh

Reputation: 62686

I don't speak swift very well, but the problem with the code is it's trying to cast the returned PFObject to a string, but you want to extract a string attribute, so (if you really want to do it):

for object in objects {
    var someString = object.valueForKey("someAttributeName") as String
    self.myDataArray.addObject(someString)
}

But please make sure you need to do this. I've noticed a lot of new parse/swift users (especially those who are populating tables) have the urge to discard the returned PFObjects in favor of just one of their attributes. Consider keeping the PFObjects and extracting the attributes later as you need them. You might find you'll need other attributes, too.

Upvotes: 1

Related Questions