Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Shorthand syntax for closures


In this section, we will look at a couple of ways to can shorten the definition of closures.

Note

To use the short hand syntax for closures is really a matter of personal preference. There are a lot of developers that like to make their code as small and compact as possible and they take great pride in doing so. However, at times, this can make code hard to read and understand by other developers.

The first shorthand syntax for closures that we are going to look at is one of the most popular and is the syntax we saw when we were using algorithms with arrays in Chapter 3, Using Collections and Cocoa Data Types. This format is mainly used when we want to send a really small (usually one line) closure to a function like we did with the algorithms for arrays. Before we look at this shorthand syntax, we need to write a function that will accept a closure as a parameter:

func testFunction(num: Int, handler:()->Void) {
  for var i=0; i < num; i++ {
    handler()...