Swift注册TableView Cell时使用AnyClass遇到的问题
AnyClass in Swift Hey there! Let's break down this issue you're facing with table view cell registration — this isn't a Swift API change, so we can rule that out right away. Let's figure out what's going wrong.
The Root of the Problem
The UITableView.register(_:forCellReuseIdentifier:) method expects an AnyClass? parameter, which is just the class object of your cell (e.g., UITableViewCell.self). The error asking for an extra NSObject parameter almost always means you're accidentally trying to pass an instance of the cell instead of the class itself.
For example, if you wrote something like this (note the parentheses after .self):
// ❌ Wrong: Trying to create an instance of the cell tableView.register(UITableViewCell.self(), forCellReuseIdentifier: "Cell")
The compiler gets confused because UITableViewCell.self() is trying to call a constructor, and since UITableViewCell's designated initializer requires parameters, it might throw a misleading error about needing an NSObject argument.
Correct Approach
The right way to pass the class object is to use .self without any parentheses. This gives you the metadata for the class, which matches the AnyClass type requirement:
// ✅ Correct: Passing the class object tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") // Same applies for custom subclasses: tableView.register(YourCustomCell.self, forCellReuseIdentifier: "CustomCell")
Quick Checks to Fix Your Code
- Double-check that you're not adding parentheses after
.self— that's the most common mistake here. - Ensure your custom cell subclass properly inherits from
UITableViewCell(if you're using one). A misconfigured inheritance chain could cause type mismatches. - If you're using a XIB for your cell, make sure you're using the correct registration method:
register(nib:forCellReuseIdentifier:), not the class-based one.
This registration API has stayed consistent across Swift versions, so the issue is almost certainly a small syntax error in your code rather than a platform change.
内容的提问来源于stack exchange,提问作者Canadian Software Engineer

