我正在尝试转换我在 this 上找到的 Objective-C 代码片段文章。这是原始代码。
.h文件
#import <Foundation/Foundation.h>
typedef void (^TableViewCellConfigureBlock)(id cell, id item);
@interface ArrayDataSource : NSObject <UITableViewDataSource>
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;
@end
.m 文件
@interface ArrayDataSource ()
@property (nonatomic, strong) NSArray *items;
@property (nonatomic, copy) NSString *cellIdentifier;
@property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock;
@end
@implementation ArrayDataSource
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock
{
self = [super init];
if (self) {
self.items = anItems;
self.cellIdentifier = aCellIdentifier;
self.configureCellBlock = [aConfigureCellBlock copy];
}
return self;
}
@end
这是我的尝试。
import Foundation
import UIKit
public class TableViewDataSource: NSObject, UITableViewDataSource {
var items: [AnyObject]
var cellIdentifier: String
var TableViewCellConfigure: (cell: AnyObject, item: AnyObject) -> Void
init(items: [AnyObject]!, cellIdentifier: String!, configureCell: TableViewCellConfigure) {
self.items = items
self.cellIdentifier = cellIdentifier
self.TableViewCellConfigure = configureCell
super.init()
}
}
但是我在 self.TableViewCellConfigure = configureCell
这一行收到一个错误,说 Use of undeclared type 'TableViewCellConfigure'。
我尝试了另一种方式。我没有为闭包声明变量,而是将其声明为类型别名。
typealias TableViewCellConfigure = (cell: AnyObject, item: AnyObject) -> Void
但随后我在上面的同一行收到一个新错误,提示 'TableViewDataSource' 没有名为 'TableViewCellConfigure' 的成员。
谁能帮我解决这个问题?
谢谢。
最佳答案
问题是您在 init
中混淆了 TableViewDataSource 和 TableViewCellConfigure。这对我来说编译得很好:
typealias TableViewCellConfigure = (cell: AnyObject, item: AnyObject) -> Void // At outer level
class TableViewDataSource: NSObject/*, UITableViewDataSource */ { // Protocol commented out, as irrelevant to question
var items: [AnyObject]
var cellIdentifier: String
var tableViewCellConfigure: TableViewCellConfigure // NB case
init(items: [AnyObject], cellIdentifier: String!, configureCell: TableViewCellConfigure) {
self.items = items
self.cellIdentifier = cellIdentifier
self.tableViewCellConfigure = configureCell
super.init()
}
}
另请注意,您使用大写字母作为属性名称 tableViewCellConfigure
- 我已更改它,因为它让我感到困惑,也可能让您感到困惑!
关于ios - 在 Swift 中将闭包作为 init 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842959/