Use cases for closures vs. functions

I've been learning Swift for the last couple weeks on the weekends and I understand, from what I've read, that functions are basically closures. But, this confuses me because obviously a feature thats 100% redundant wouldn't be implemented, so when should you use closures vs functions? Are there times you can only use closures in Swift, or can you always use them interchangeably?

  • Each time you have a closure you can put a function. If code is called only once, it may not worth using a function rather than just writing the closure. If the same code is called many times may be a function will be better for maintenance.

Add a Comment

Replies

They are not totally redundant. Major difference is a convenience of writing and the capability to name parameters or the func itself. This improves largely readabilty of code.

We could say closures are a stripped down version of func. But they are functionally equivalent.

See more details here: https://medium.com/@anuj.rai2489/closure-vs-function-vs-protocol-in-swift-94d0ecd03406