【发布时间】:2014-09-15 07:38:03
【问题描述】:
我正在尝试转换我在this 文章中找到的 Objective-C 代码 sn-p。这是原始代码。
.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应该是init(items: [AnyObject]!, cellIdentifier: String!, configureCell: TableViewCellConfigure)而不是configureCell: TableViewDataSource -
@Grimxn 哦该死!接得好。我改变了它,但现在我得到一个新的错误。 使用未声明的类型'TableViewCellConfigure
标签: ios swift closures init-parameters