© Yanis Zafirópulos 2019
Yanis ZafirópulosSwift 4 Recipeshttps://doi.org/10.1007/978-1-4842-4182-0_5

5. Functions

Yanis Zafirópulos1 
(1)
Granada, Spain
 

In programming, a function is nothing but a named section of code – with or without arguments – which performs a specific task and may possibly also return a value. In this chapter, we’ll see how you can get the most out of them in Swift.

5.1 Define and call a function

Problem

I want to define and call a new function from scratch.

Solution

Let’s create a function sayHello.
func sayHello() {
      // This is the function 'body' - aka the statements
      print("Hello World!")
}

What about calling our function?

Note

Even without arguments, we must use parentheses

sayHello()

How It Works

Functions, by definition, ...

Get Swift 4 Recipes: Hundreds of Useful Hand-picked Code Snippets 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.