-
Notifications
You must be signed in to change notification settings - Fork 10.5k
[SR-5819] Suggest as? AnyHashable
when as? Equatable
or as? Hashable
is attempted
#48389
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Comment by Kevin Lundberg (JIRA) I'm taking a stab at this, and I'm wondering if it's enough to just check any place where someone tries to do `blah as? Equatable`, or should this fix-it only apply inside conditional statements? Should it also apply for `as`/`as!`, and in a case like this? `let x: Equatable = "X"` |
I'd rather not recommend casting to AnyHashable, which has subtleties of its own. Wouldn't a protocol shared by all your Equatable objects be a better idiom? |
The subtleties should be transparent to most people, they only affect bridged ObjC types. If you have a protocol shared by all your Equatable objects, that protocol still can't refine Equatable without losing support for the existential type, and if it doesn't refine Equatable, you'll need to cast to AnyHashable to invoke |
The protocol doesn't have to look like Equatable to have the operation:
But if all implementations of this are going to start with a type-check, maybe it doesn't matter. |
Comment by Suyash Shekhar (JIRA) Are there any updates or decision for this bug? |
We haven't discussed this specifically recently. I still think this is a good idea, I don't know how @belkadan feels. |
I still don't think it's a good idea, but I don't feel super strongly about it. |
Hi @jckarter, I was looking at this and I think there is a decent solution now without extension Equatable {
func isEqualTo(_ other: Any) -> Bool {
guard case let other as Self = other else {
return false
}
return self == other
}
}
let a = 1 as Any
let b = 2 as Any
if let areEqual = (a as? any Equatable)?.isEqualTo(b) {
return areEqual
} Something else is that the following would not work (as intended) with struct S: Equatable {
var x: Int
}
let a = S(x: 0) as Any
let b = S(x: 10) as Any
if let a = a as? AnyHashable, let b = b as? AnyHashable {
return a == b
} It is not as convenient of course; it depends on the user defining the above extension or similar. An alternative could be an |
Additional Detail from JIRA
md5: 5e4ffb6d40f711123adf86651f9a3a8f
Issue Description:
If you have two values of type
Any
or otherwise opaque type and you want to test whether they're equal, it's natural to try to write something like:Maybe someday that will work, but in the meantime dynamically casting to
AnyHashable
can get the desired effect. It'd be nice QoI to have a diagnostic telling people they can do this when they try similar things that don't.The text was updated successfully, but these errors were encountered: