[英]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.