O'Reilly logo

Xcode 7 Essentials - Second Edition by Jayant Varma, Brett Ohland

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Functions and closures

A function is simply a self-contained block of code that's given an identifiable name. You can then call these blocks of code, pass values into them, and even get values out of them. Closures are simply functions that can be passed around like any other type of object. They have the added ability to capture variables and constants from where they were declared, closing over them, and making those values available any time the closure is called.

At their most basic, a function can look like this:

func printGreeting() {
  print("Hello from a function")
}

The keyword func is used to declare the function's name and any code you want to run is contained within the braces {}.

Calling the function is as easy as using the function name ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required