Chapter    27

Functions

You can declare a function anywhere with the func keyword. Functions are used to organize code into reusable chunks that take input parameters and return results. Listing 27-1 shows an example of a function that returns the string “Hello World.”

Listing 27-1. Simple Function

func getPhrase() -> String{    return "Hello World"}

In Listing 27-1, the function declaration starts with the func keyword followed by the name of the function. After the function name in Listing 27-1, you have (), which designates an empty parameter list. The return type of the function (String) is written after the return type symbol ->.

After the function return type, you have a code block designated in the curly brackets, {}. The getPhrase() ...

Get Swift Quick Syntax Reference 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.