2

After reading that functions are just a special case of closures, being a named constant closure, is there any reason to use a function over a closure? I ran into a problem recently where I needed to pass my functions into a method for sequential animation and ended up needing to transform my functions into closures. So with that disadvantage and loss of flexibility, why would I ever want to use functions over closures?

1 Answer 1

1

I advise you to use closures whenever you need to use this code just once and only in that exactly point where you implement it in your whole code.

If you need to reuse the logic of a block of code, the best way is to encapsulate your code inside a function and use it as a callback.

I can´t imagine a situation when you would need to convert all your functions into closures. All you need to do is create a function that fits with your closure signature.

Sign up to request clarification or add additional context in comments.

4 Comments

I think this answer is a bit too absolute. There are many situations when you'd want to use a closure more extensively than inline and only once. I think the use case for each is a bit more finessed than this. Also, functions can be passed in anywhere a closure can.
@Logan "functions can be passed in anywhere a closure can"...My original mistake was believing you could not pass a function as a parameter, but after testing again, because of what you wrote, I found my mistake was passing in "foo()" rather than "foo". My apologies on such a simple mistake, I was under the impression that would cause an error, but after testing again in playground it clearly does not. Thus, I see the benefit of functions over closures, is similar to using "let" over "var", which is clarity and immutability.
@AndrewJohnson - It's important to remember that anything inside of a function will be captured strongly. So if you have an instance method that references self, self will be captured.
@Logan, I just try say that I don´t see motivation to use closure in situations where you need to use the same logic twice or more in the same project. In this case, I think the smartest way would be pass a funcion as parameter than repeat the same block of code through the whole source code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.