I come from a VB background (and lots of other languages), and now I'm learning Swift. I just reached the part about closures, and I've been searching for an article about when a function is to be preferred over a closure, and I haven't found any yet.
It seems that closures have the advantage that I can call it without having to identify all of the parameters by name. And (though I haven't tested it), another closure advantage may be that it's definition may be dynamic and possibly changed at runtime.
But with these advantages of closures, what's a case where a function would have advantages over a closure?
It seems that closures have the advantage that I can call it without having to identify all of the parameters by name. And (though I haven't tested it), another closure advantage may be that it's definition may be dynamic and possibly changed at runtime.
But with these advantages of closures, what's a case where a function would have advantages over a closure?
A closure let you write a func "in line", without having to define an external explicit func:
can be replaced by more condensed
Apple Inc. « The Swift Programming Language (Swift 4). » Apple Books.
But func and closures are very close.
You can name a closure
But it is much easier to pass arguments through a func.
So, which is better depends on the context of the code.
Code Block func backward(_ s1: String, _ s2: String) -> Bool { return s1 > s2 } var reversedNames = names.sorted(by: backward)
can be replaced by more condensed
Code Block reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )
Apple Inc. « The Swift Programming Language (Swift 4). » Apple Books.
But func and closures are very close.
You can name a closure
Code Block let closure = { print("")}
But it is much easier to pass arguments through a func.
So, which is better depends on the context of the code.