使用存储在参数中的类型转换对象

陛下

如何使用类型(存储在参数中)转换对象?

例:

假设我有一个简单的enum像这样:

enum SettingsAction {
    case contactUs

    var cellType: UITableViewCell.Type {
        return TitleSettingsTableViewCell.self
    }
}

然后,我尝试使用创建对象cellType,如下所示:

let settingsAction = SettingsAction.contactUs
let cellType = settingsAction.cellType
let cell = tableView.dequeueReusableCell(withIdentifier: "\(cellType)", for: indexPath) as! cellType

我收到以下错误:

Cannot find type 'cellType' in scope

似乎无法使用参数进行强制转换,从而导致一些奇怪的预编译器错误。

有正确的方法来实现我正在尝试的功能吗?

塔伦(Tarun)

试试这样的事情-

enum SettingsAction {
    case contactUs

    func cellForRow(at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell {
        switch self {
        case .contactUs:
            return tableView.dequeueReusableCell(withIdentifier: "TitleSettingsTableViewCell", for: indexPath) as! TitleSettingsTableViewCell
        }
    }
        
}

Update Swift不允许您使用Type存储在仅在运行时可用的变量中的信息。类型推断在编译时需要此信息。您必须以一种或另一种方式放弃灵活性。这是解决同一问题的另一种尝试-远非理想-确实可以满足本用例的需要。

class UserInfoTableViewCell: UITableViewCell {
    var userProperty: Bool = false
}
class ContactUsTableViewCell: UITableViewCell {
    var contactProperty: Bool = false
}
class LegalTableViewCell: UITableViewCell {
    var legalProperty: Bool = false
}

class SettingsCellCreator<T: UITableViewCell> {
    func cellForRow(at indexPath: IndexPath, in tableView: UITableView) -> T {
        tableView.dequeueReusableCell(withIdentifier: "\(T.self)", for: indexPath) as! T
    }
}

private let userInfoCellCreator = SettingsCellCreator<UserInfoTableViewCell>()
private let contactUsCellCreator = SettingsCellCreator<ContactUsTableViewCell>()
private let legalCellCreator = SettingsCellCreator<LegalTableViewCell>()

class ViewController: UIViewController, UITableViewDataSource {
    
    enum CellType {
        case userInfo
        case contactUs
        case legal
    }
    
    private var rows: [CellType] = [
        .userInfo,
        .contactUs,
        .contactUs,
        .legal,
        .legal
    ]
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        rows.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch rows[indexPath.row] {
        case .userInfo:
            let cell = userInfoCellCreator.cellForRow(at: indexPath, in: tableView)
            cell.userProperty = true
            return cell
            
        case .contactUs:
            let cell = contactUsCellCreator.cellForRow(at: indexPath, in: tableView)
            cell.contactProperty = true
            return cell
            
        case .legal:
            let cell = legalCellCreator.cellForRow(at: indexPath, in: tableView)
            cell.legalProperty = true
            return cell
        }
    }
    
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章