Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

SWIFT: Blocks to Closure

I have the following function written in Objective C using blocks and I am trying to convert it to swift, but I am banging my head against the wall and can't get it sorted.

Here is the code in Objective C

typedef void (^ResponseBlock) (BOOL succeeded, NSArray* data);

- (void)findAllMediaFromDate:(NSDate*)createdAtDate block:(ResponseBlock)block
{
    NSMutableArray *results = [NSMutableArray array];
    PFQuery *query = [PFQuery queryWithClassName:PARSE_MODEL_ACTIVITIES];
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            for (ActivityObject *object in objects) {
                if ([object.media.type isEqualToString: @"video"] || [object.media.type  isEqualToString: @"photo"]) {
                    [results addObject:object];
                }
            }

            block(YES, results);
        }
        else {

        }
    }];
}

Now here is what I have in SWIFT. It's a different function body, but the syntax I am trying is the same...

    func userQuery (){   //This needs to return an array as ABOVE
        var results = [UserModel]()
        println("NM: userQuery")
        var query = UserModel.query()
        query.whereKey("objectId", equalTo:"7N0IWUffOZ")
        query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
            if (objects != nil) {
                NSLog("yea")
                for object in objects{
                    results.append(object as UserModel)
                    //Need to return the array to the userQuery function
                }

            } else {
                NSLog("%@", error)
            }

        }

    }