SWIFT Closure语法 - 从Objective C转换

时间:2014-10-12 16:50:11

标签: objective-c swift closures

我使用块在Objective C中编写了以下函数,我正在尝试将其转换为swift,但是我正在撞墙而不能将其排序。

以下是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 {

    }
}];
}

现在这就是我在SWIFT中所拥有的。它是一个不同的函数体,但我尝试的语法是相同的......

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)
        }

    }

}

```

1 个答案:

答案 0 :(得分:2)

你可以像这样添加closure参数:

func userQuery(completionHandler: (succeeded: Bool, array: [UserModel]?) -> ()) {
    // do your other stuff here

    if objects != nil {
        // build results
        completionHandler(succeeded: true, array: results)
    } else {
        // return failure
        completionHandler(succeeded: false, array: nil)
    }
}

显然,将array参数更改为您想要的任何内容(重命名,更改类型等),但基本思路是使用可选的数组返回类型。

你可以使用尾随闭包语法来调用它,如下所示:

userQuery() {
    success, results in

    if success {
        // use results here
    } else {
        // handle error here
    }
}

顺便说一句,如果你喜欢Objective-C typedef模式,Swift中的等价物是typealias

typealias ResponseClosure = (succeeded: Bool, array: [UserModel]?) -> ()

func userQuery(completionHandler: ResponseClosure) {
    // the same as above
}