0

この記事で見つけた 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()
    }

}

しかし、この行でUse of undeclared type 'TableViewCellConfigure'self.TableViewCellConfigure = configureCellというエラーが表示されます。

別の方法を試しました。クロージャの変数を宣言する代わりに、typealias として宣言しました。

typealias TableViewCellConfigure = (cell: AnyObject, item: AnyObject) -> Void

しかし、その後、上記の同じ行で、「TableViewDataSource」には「TableViewCellConfigure」という名前のメンバーがないという新しいエラーが表示されます。

誰でもこれを解決するために私を助けてもらえますか?

ありがとうございました。

4

1 に答える 1

1

問題は、TableViewDataSource と TableViewCellConfigure を混同したことですinit。これは私にとってはうまくコンパイルされます:

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。私とあなたを混乱させたので変更しました。

于 2014-09-15T08:24:59.787 に答える