Accessing Class var on AnyClass variable in Swift 4

485 Views Asked by At

In Swift 3.2 this (let id = row.tableViewCellClass?.reuseIdentifier) worked:

class DrillDownTableViewCell {
    class var reuseIdentifier: String
    {
        return String(describing: self)
    }
}

class RowViewModel: NSObject
{
    var tableViewCellClass: AnyClass?
}

class Foo {
    var row : RowViewModel?
    func setup() {
        row = RowViewModel()
        row?.Class = DrillDownTableViewCell.self
    }

    func doThings()  {
        let id = row?.tableViewCellClass?.reuseIdentifier
    }
}

After my Swift 4 update, it's showing "Instance member 'reuseIdentifier' cannot be used on type 'AnyObject'.

How would I access a class variable on a class who's metaType information is stored in an AnyClass variable?

1

There are 1 best solutions below

0
On

(I assume you mean to have a ? after row in doThings(). I assume that's a typo and not part of the question. There are several other ? missing here and some other typos that I won't dive into.)

If you expect tableViewCellClass to have a reuseIdentifier class property, then it isn't of type AnyClass. There are many classes that don't have that property. You want classes that conform to a protocol:

protocol Identifiying {
    static var reuseIdentifier: String { get }
}

So your model requires an Identifying class:

class RowViewModel: NSObject {
    var tableViewCellClass: Identifiying.Type?
}

Then you can use this as you're expecting.