Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test functions and closures for equality?

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 
like image 591
Jessy Avatar asked Jun 08 '14 23:06

Jessy


People also ask

How do you find the equality of a function?

Two functions are equal if they have the same domain and codomain and their values are the same for all elements of the domain.

What is the difference between closures and functions?

Difference between Function and ClosureFunction is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.

Why use closures?

Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.


2 Answers

Chris Lattner wrote on the developer forums:

This is a feature we intentionally do not want to support. There are a variety of things that will cause pointer equality of functions (in the swift type system sense, which includes several kinds of closures) to fail or change depending on optimization. If "===" were defined on functions, the compiler would not be allowed to merge identical method bodies, share thunks, and perform certain capture optimizations in closures. Further, equality of this sort would be extremely surprising in some generics contexts, where you can get reabstraction thunks that adjust the actual signature of a function to the one the function type expects.

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.

like image 178
drewag Avatar answered Oct 14 '22 03:10

drewag


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:

var handler:Handler = Handler(callback: { (message:String) in             //handler body })) 
like image 29
tuncay Avatar answered Oct 14 '22 05:10

tuncay