Maciej Swic
Maciej Swic

Reputation: 11359

Store Swift Type in variable

I have a data model for a UITableViewCell that looks like this:

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
    }
}

The idea is to put these in an array to facilitate building a settings view using a UITableViewController, and when requesting a cell i can just query the model for both the identifier and the cell Type. But i cannot figure out what keyword to use instead of Type. I have tried Type, AnyClass, UITableViewCell.Type and they all give rise to type assignment errors when i try to instantiate the model class.

Upvotes: 1

Views: 2806

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

The syntax you want is UITableViewCell.Type. This is the type of something that is a subclass of UITableViewCell. You can accept the type of any class using AnyClass, but you should usually avoid that. Most of the time, if you think you want AnyClass, you really want a generic.

When you try to pass your type to this init, it'll be something like:

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

Referring to types directly is a little uncommon, so Swift requires that you be explicit by adding .self to it.

You may in fact want a generic here anyway. I'd probably write it this way:

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 } )

Upvotes: 2

Related Questions