2

so here's the problem that I'm facing. Take a look

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell_Title") as! ExpenseTableViewCell_Title
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell_SaveCanel") as! ExpenseTableViewCell_SaveCanel
        return cell
    }
}

what i want to do is, use cell identifier string as cell type.(i.e. ExpenseTableViewCell_Title, ExpenseTableViewCell_SaveCanel).

I do have cell identifier array.

var TableCell:[ExpenseCellType] = [.ExpenseTableViewCell_Title, .ExpenseTableViewCell_SaveCanel]

Right now I only have two types of cell. But this number will go high. And I don't want to use if/else condition or switch case.

Thank in advance.

1
  • Swift is strict with type checking. So you can't avoid this. Commented Dec 30, 2016 at 9:26

2 Answers 2

3

Can make it shorter with extension:

extension UITableView {
    func dequeueReusable<T>(type: T.Type, index: IndexPath) -> T {
        return self.dequeueReusableCell(withIdentifier: String(describing: T.self), for: index) as! T
    }
}

Use it like this, will return ExpenseTableViewCell_Title type cell:

let cell = tableView.dequeueReusable(type: ExpenseTableViewCell_Title.self, index: indexPath)

Just store your class in the array like [ExpenseTableViewCell_Title.self, ExpenseTableViewCell_SaveCanel.self] and pass it to this function

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I'll try this.
2

You can use function NSClassfromString but you will need namespace for getting class from String.

I have created example here to use it. Example:

func getClassFromString(_ className: String) -> AnyClass! {


    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
    let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!;

    return cls;
}


    class customcell: UITableViewCell {

        }   

    let requiredclass = getClassFromString("customcell") as! UITableViewCell.Type
    let cellInstance = requiredclass.init()

1 Comment

thanks for your answer, but I could find any function named "stringClassFromString". although I did tried "NSClassFromString". That didn't worked either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.