How Closures Work and Why They’re Awesome
Swift defines a closure syntax that is different from the regular function syntax. This syntax allows you to do a couple things: It allows you to infer the type of the object from the context, and it allows you to return a value without actually writing return
. There are several different ways to write closures in Swift, and some of them take very little code. If you are used to replacing or rewriting Objective-C syntax, you may have seen blocks as the last parameter of a function. Swift allows you to write closures outside functions when they are the last parameters. This gives you a nice clean-looking syntax.
Let’s take a look at the sort
function in Swift. For this example, you are going to pass two ...
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.