0

The Parse documentation provides examples of queries using Swift, and they show an example accessing a built-in field like objectId or count, but what about accessing one of the columns of the object?

    var query = PFQuery(className: "MyObject")
    query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]!, error: NSError!) -> Void in
            if !(error != nil) {
                for object in objects {
                    println(object["name"])
            }
            else {
                println("%@", error)
            }
    }

Gets the error "AnyObject" is not convertible to string.

object.objectForKey("name")

Also gives an error: "Could not find an overload for 'objectForKey' that accepts the supplied arguments"

Now I also tried "as PFObject" or something similar, but it also results in errors plus Parse's documentation doesn't show anything like that. "Type '[AnyObject]' cannot be implicitly downcast to 'PFObject'; did you mean to use 'as' to force downcast?"

Then I apply the fix, the new error is "Type 'PFObject' does not conform to protocol 'SequenceType'

Tried also downcasting inside the loop with

let pf = object as PFObject

but that doesn't seem to help because when I do

let name = pf["name"]

I get "'AnyObject' is not convertible to 'String'"

Thanks for your help. I'm sure I'm missing something obvious, since I haven't found anything yet;

2
  • 1
    have you tried let name = pf["name"] as String ? Commented Oct 1, 2014 at 7:55
  • That did it, thank you. So you just always have to cast things like this? Add it as an answer below and I will select it. Commented Oct 2, 2014 at 1:32

2 Answers 2

7

You need to explicitly cast the attribute you are retrieving -

let name = pf["name"] as String
Sign up to request clarification or add additional context in comments.

Comments

1

This worked for me:

    var query = PFQuery(className: "People")
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in

        if error == nil {

            // query successful - display number of rows found
            println("Successfully retrieved \(objects.count) people")

            // print name & hair color of each person found
            for object in objects {

                let name = object["name"] as NSString
                let color = object["hairColor"] as NSString

                println("\(name) has \(color) hair")

            }
        } else {

            // Log details of the failure
            NSLog("Error: %@ %@", error, error.userInfo!)
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.