I think there are 2 sides to this.
Firstly, is this a good idea:
I’d agree NSStringFromClass is a safer way to get the canonical name. Additionally, you’ve got the problem that class names give you very little (aka no) collision avoidance. There’s a risk someone on a multi-dev codebase who doesn’t use your reuse style may use the class name directly in code. Best to use some form of obfuscated name instead that at least has very low risk of collision (you can’t fix these classes to make the risk zero).
Secondly, is this an SDK issue, or a language issue?
From what has been shown here, it seems this is an SDK issue, not a language issue. Indeed, this stuff is still a problem if we use this with Objective-C. Updating Swift as a language to enable such an isolated use case seems a bit like using a sledgehammer to scratch your back. Even in Obj-C, iOS is only one platform. UIKit, despite being common, is again only one framework on that platform.
At this stage it might just be a better idea for us to house this extension in our codebases, rather than try to “fix” such an isolated problem in the language itself. Especially since, as I’ve mentioned, even the fix is somewhat flaky.
It is an interesting concept to add an identifier to each class for String-based identification, but I’m trying to work out why were wouldn’t just use NSStringFromClass, which whilst not being quite as clean as a class property, would be just as valid. Also, when investigating the risk of collisions, it seems this may not be what you’re after anyway.
@fahidattique55 I have a slightly different implementation: I have a protocol called DefaultReusable
which vends defaultReuseIdentifiers
for each class, and prepends a meaningful word to the reuse identifier that prints in logs and debugging.
protocol DefaultReusable: AnyObject {
static var defaultReuseIdentifier: String { get }
}
extension DefaultReusable {
static var defaultReuseIdentifier: String {
return “DefaultReusable_” + NSStringFromClass(self)
}
}
This has a few wins:
- It means I can tag classes that are default reusable. I actually extend UICollectionReusableView and UITableViewCell without overloading every class, and without writing it multiple times
- It provides clarity for users as to intent behind it, rather than a global string extension everyone can access that no one else will use.
- It allows overriding in all implementing the extension to do something different if it makes sense.
- It has built in obfuscation with the prepended String which also aids in logging and debugging.