The book says that "functions and closures are reference types". So, how do you find out if the references are equal? == and === don't work.
func a() { }
let å = a
let b = å === å // Could not find an overload for === that accepts the supplied arguments
Here is how the Catterwauls are dealing with this:
This is a great question and while Chris Lattner intentionally doesn't want to support this feature I, like many developers, also can't let go of my feelings coming from other languages where this is a trivial task. There are plenty of
unsafeBitCast
examples, most of them don't show the full picture, here's a more detailed one:The interesting part is how swift freely casts SwfBlock to ObjBlock, yet in reality two casted SwfBlock blocks will always be different values, while ObjBlocks won't. When we cast ObjBlock to SwfBlock, the same thing happens to them, they become two different values. So, in order to preserve the reference, this sort of casting should be avoided.
I'm still comprehending this whole subject, but one thing I left wishing for is ability to use
@convention(block)
on class / struct methods, so I filed a feature request that needs up-voting or explaining why it's a bad idea. I also get a sense this approach might be bad all together, if so, can anyone explain why?Chris Lattner wrote on the developer forums:
https://devforums.apple.com/message/1035180#1035180
This means that you should not even try to compare closures for equality because optimizations may affect the outcome.
Here is one possible solution (conceptually the same as 'tuncay' answer). The point is to define a class that wraps some functionality (e.g. Command):
Swift:
Java:
I've been looking for the answer, too. And I've found it at last.
What you need is the actual function pointer and its context hidden in the function object.
And here is the demo:
See the URLs below to find why and how it works:
As you see it is capable of checking identity only (the 2nd test yields
false
). But that should be good enough.I searched a lot. There seems to be no way of function pointer comparison. The best solution I got is to encapsulate the function or closure in an hashable object. Like:
Well it's been 2 days and nobody has chimed in with a solution, so I'll change my comment to an answer:
As far as I can tell, you can't check equality or identity of functions (like your example) and metaclasses (e.g.,
MyClass.self
):But – and this is just an idea – I can't help but notice that the
where
clause in generics appears to be able to check equality of types. So maybe you can leverage that, at least for checking identity?