[英]Passing a closure as a init parameter in Swift
我想转换一个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
说了使用未声明类型'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
使用了大写字母-我已对其进行了更改,因为它使我,甚至可能使您感到困惑!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.