Search code examples
swiftpfqueryparse-serverpfobjectheroku-api

How to use PFQuery getObjectWithId?


Working with PFObject and PFQuery I am having trouble debugging this piece of code:

.......

if let someContents = object.valueForKey("contents") {
    let query = PFQuery(className: "TheContentList")
    do {let object = try query.getObjectWithId(someContents.objectId)
        print(object)
    } catch {
        print(error)
    }
}

With the code above I get this compiler message for the line with getObjectWithId:

Cannot convert value of type 'String?!' to type 'String' in coercion

If I change:

query.getObjectWithId(someContents.objectId)

to:

query.getObjectWithId("xyz23AcSXh")

It compiles and inside the debugger I get this:

(lldb) p someContents.objectId
(String?!) $R4 = "xyz23AcSXh"

And the program prints an object as expected.

So the question is: how should I write the line query.getObjectWithId to be able to use what is inside someContents?


Solution

  • Your property objectId, is an Explicitly Unwrapped Optional, of an Optional. If you're sure it contains a String, unwrap it using:

    let object = try query.getObjectWithId(someContents.objectId!!)
    

    Otherwise, if you're not sure:

    if let objectId = someContents.objectId, id = objectId {
        let object = try query.getObjectWithId(id)
    }