swift - 将 Swift 类型存储在变量中

标签 swift generics swift2

我有一个 UITableViewCell 的数据模型,如下所示:

class SettingsContentRow {
    var title: String
    var cellType: Type // How do i do this?
    var action:((sender: UITableViewCell.Type) -> ())?

    var identifier: String {
        get { return NSStringFromClass(cellType) }
    }

    init(title: String, cellType: Type) {
        self.title = title
        self.cellType= cellType
    }
}

这个想法是将它们放入一个数组中,以便于使用 UITableViewController build设置 View ,并且在请求单元格时,我可以查询模型以获取标识符和单元格键入。但我不知道使用什么关键字来代替 Type。我尝试过 TypeAnyClassUITableViewCell.Type,当我尝试实例化模型类时,它们都会引起类型分配错误。

最佳答案

您想要的语法是UITableViewCell.Type。这是 UITableViewCell 子类的类型。您可以使用 AnyClass 接受任何类的类型,但通常应该避免这样做。大多数时候,如果您认为需要 AnyClass,那么您确实需要一个泛型。

当您尝试将类型传递给此 init 时,它将类似于:

SettingsContentRow("title", cellType: MyCell.self)

直接引用类型有点不常见,因此 Swift 要求您通过添加 .self 来显式地引用类型。

无论如何,您实际上可能需要一个泛型。我可能会这样写:

final class SettingsContentRow<Cell: UITableViewCell> {
    typealias Action = (Cell) -> ()
    let title: String
    let action: Action?

    var identifier: String {
        get { return NSStringFromClass(Cell.self) }
    }

    init(title: String, action: Action?) {
        self.title = title
        self.action = action
    }
}

class MyCell: UITableViewCell {}

let row = SettingsContentRow(title: "Title", action: { (sender: MyCell) in } )

关于swift - 将 Swift 类型存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35555549/

相关文章:

ios - 放大 UIView 而不会像素化

ios - 快速饼图切片

java - 绕过 Java/GWT 中的类型删除

generics - 为什么 F# 中的这个接口(interface)实现无法编译?

ios - 按数组中的对象分组

Swift 协议(protocol)比较

ios - swift 2 + Xcode 7 : Sound playing when wrong button is pressed

swift - 停止 urlRequest onViewDisappear

debugging - 调试 UIButton 时出现问题

java - get-put原理的解释