Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, Parse and Xcode 6 beta6

My query to Parse now raises a swift compiler error in Xcode 6 beta6 (see error below). It was working fine previously (and my example is simple, and comes from Parse's documentation). I've changed one thing coming from Xcode 6 beta 6: from "objects: AnyObject[]!" to "objects: [AnyObject]!" (due to error "Array types are now written with the brackets around the element type")

query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if !(error != nil) {
            NSLog("Successfully retrieved \(objects.count) objects.")
            for object : PFObject! in objects { ... } ...

// ERROR: Type [AnyObject] cannot be implicitely downcast to 'PFObject', did you mean to use 'as' to force downcast?

And if I force the downcast as suggested by the previous error, I get another error:

for object : PFObject! in objects as PFObject {
       ...
}

// ERROR: Type PFObject does not conform to protocol SequenceType

And if I change objects: [AnyObject]! by objects: [PFObject]! I get the following error:

query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]!, error: NSError!) -> Void in
        if !(error != nil) {
            for object : PFObject! in objects {

// ERROR: AnyObject is not identical to PFObject

ANSWER TO FIX THE COMPILER ISSUE

Correct answer is below (Xcode suggested the downcast to PFObject while the downcast is on "objects", an array):

for object : PFObject! in objects as [PFObject] {
       ...
}

UPDATED CORRECT ANSWER for execution time

The above answer was fixing the compiler issue, not the execution. After chatting with Parse guys, their documentation is not up-to-date since beta 6 is out. To loop on PFObjects objects returned from a query, simply do a "for object in objects {} ":

 query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]!, error: NSError!) -> Void in
        if (error == nil) {
           for object in objects {
            ...
            } ...
 }
like image 658
Tom - Lunabee.com Avatar asked Mar 15 '26 19:03

Tom - Lunabee.com


1 Answers

You're trying to downcast an array I believe. What happens if you change this:

for object : PFObject! in objects as PFObject {
       ...
}

To this:

for object: PFObject in objects as [PFObject] {
       ...
}

I also wanted to point out that this might not do what you're intending:

if !(error != nil) {

The additional exclamation point preceding the parenthesis is creating a double negative which can make your intentions ambiguous.

UPDATE

As pointed out in comments, Parse suggests to do a simple for-in loop without any explicit downcasting.

for object in objects {}
like image 130
Logan Avatar answered Mar 17 '26 13:03

Logan