Update:
The OP added this comment clarifying the requirements:
I need the 'key' to be different for 2 instances of UIView. I want that key to be the same every time for that particular instance i.e. the key shouldn't change if the app is restarted or the view instance is destroyed and recreated. I can use this key as key in caching. Another use case can be to use it as accessibilityIdentifier to help with UITesting.
In that case, I suggest to not even think about using ✨magic✨. Just explicitly give your view instances an identifier. You could also totally just reuse existing properties on UIView
like tag
or accessibilityIdentifier
. If that's not enough or not convenient enough, subclass:
class IdentifiableView: UIView {
public private(set) var identifier: String
init(frame: CGRect, identifier: String) {
self.identifier = identifier
super.init(frame: frame)
self.accessibilityIdentifier = identifier
}
init() {
fatalError("Must use init(frame:identifier:)")
}
override init(frame: CGRect) {
fatalError("Must use init(frame:identifier:)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("Must use init(frame:identifier:)")
}
}
// Usage
let firstView = IdentifiableView(frame: .zero, identifier: "First View")
firstView.identifier
firstView.identifier
let otherView = IdentifiableView(frame: .zero, identifier: "Second View")
otherView.identifier
otherView.identifier
If, according to your comment, you simply want "objects to return a unique key that does not change", you could simply use their memory address:
extension UIView {
var key: String {
return "\(Unmanaged.passUnretained(self).toOpaque())"
}
}
let firstView = UIView()
firstView.key // -> "0x00007fbc29d02f10"
firstView.key // -> "0x00007fbc29d02f10"
let otherView = UIView()
otherView.key // -> "0x00007fbc29d06920"
otherView.key // -> "0x00007fbc29d06920"
For each instance of UIView
you create this will return a unique value that will not change.