O'Reilly logo

Beginning Swift Programming by Wei-Meng Lee

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

5 Functions

WHAT YOU WILL LEARN IN THIS CHAPTER:            

  • How to define and call a function
  • How to define input parameters
  • How to return a value or multiple values from a function
  • How to define external parameter names
  • How to define default parameter values
  • How to define variadic parameters
  • How to define constant and variable parameters
  • How to define in-out parameters
  • How to define and call function type variables
  • How to return a function type from a function
  • How to define nested functions

A function is a group of statements that perform a specific set of tasks. For example, a particular function may calculate the bonus of an employee based on a few parameters, such as his or her performance rating, number of years in the company, and so on. A function may also return a value, such as the amount of bonus to which an employee is entitled. In Swift, a function has a name, and it may also accept parameters and optionally return a value (or a set of values). Functions in Swift work similarly to traditional C functions, and they also support features such as external parameter names, which enables them to mirror the verbosity of Objective-C methods.

DEFINING AND CALLING A FUNCTION

In Swift, a function is defined using the func keyword, like this:

func doSomething() {
   println("doSomething")
}

The preceding code snippet defines a function called doSomething. It does not take in any inputs (known as parameters) and does not return a value (technically it does return a Void

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