5

我正在尝试在 Swift 中实现示例 LoopBack iOS 应用程序

创建 LoopBack iOS 应用程序:第一部分

我在从 ObjectiveC 翻译时遇到了一些麻烦

- (void) getBooks
{
    //Error Block
    void (^loadErrorBlock)(NSError *) = ^(NSError *error){
        NSLog(@"Error on load %@", error.description);
    };
    void (^loadSuccessBlock)(NSArray *) = ^(NSArray *models){
        NSLog(@"Success count %d", models.count);
        self.tableData = models;
        [self.myTable reloadData];
    };
    //This line gets the Loopback model "book" through the adapter defined in AppDelegate
    LBModelRepository *allbooks = [[booksAppDelegate adapter] repositoryWithModelName:prototypeName];
    //Logic - Get all books. If connection fails, load the error block, if it passes, call the success block and pass allbooks to it.
    [allbooks allWithSuccess:loadSuccessBlock  failure:loadErrorBlock];
};

这是我的版本

func getBooks() {
    var errorBlock = {
        (error: NSError!) -> Void in
        NSLog("Error on load %@", error.description)
    }

    var successBlock = {
        (models: NSArray!) -> Void in
        NSLog("Success count %d", models.count)
        self.tableData = models
        self.booksTable.reloadData()
    }

    // get the "book" model
    var allBooks: LBModelRepository = adapter.repositoryWithModelName(prototypeName)

    // get all books
    allBooks.allWithSuccess(successBlock, errorBlock)
}

但我在调用 allWithSuccess 时遇到编译器错误:

无法将表达式类型“Void”转换为类型“LBModelAllSuccessBlock!”

我错过了什么?

更新:

如果我如下声明成功块,它将起作用:

    var successBlock = {
        (models: AnyObject[]!) -> () in
        self.tableData = models
        self.booksTable.reloadData()
    } 
4

1 回答 1

1

感谢你的回答!!!!

如果有人正在寻找 Swift 和 LoopBack iOS SDK 的最新版本,它对我来说是这样的:

func getBooks() {
    // Error Block
    let errorBlock = {
        (error: NSError!) -> Void in
        NSLog("Error on load %@", error.description)
    }

    // Success Block
    let successBlock = {
        (models: [AnyObject]!) -> () in
        self.tableData = models
        self.myTable.reloadData()
    }

    // This line gets the Loopback model "book" through the adapter defined in AppDelegate
    let allBooks:LBPersistedModelRepository = AppDelegate.adapter.repositoryWithModelName(prototypeName, persisted: true) as! LBPersistedModelRepository

    // Logic - Get all books. If connection fails, load the error block, if it passes, call the success block and pass allbooks to it.
    allBooks.allWithSuccess(successBlock, failure: errorBlock)
}
于 2015-12-22T08:56:31.310 回答