Reader small image

You're reading from  iOS 17 Programming for Beginners - Eighth Edition

Product typeBook
Published inOct 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781837630561
Edition8th Edition
Languages
Tools
Right arrow
Author (1)
Ahmad Sahar
Ahmad Sahar
author image
Ahmad Sahar

Ahmad Sahar is a trainer, presenter, and consultant at Tomafuwi Productions, specializing in conducting training courses for macOS and iOS, macOS Support Essentials certification courses, and iOS Development courses. He is a member of the DevCon iOS and MyCocoaHeads online communities in Malaysia and has conducted presentations and talks for both groups. In his spare time, he likes building and programming LEGO Mindstorms robots.
Read more about Ahmad Sahar

Right arrow

Functions and Closures

At this point, you can write reasonably complex programs that can make decisions and repeat instruction sequences. You can also store data for your programs using collection types. As the programs you write grow in size and complexity, it will become harder to comprehend what they do.

To make large programs easier to understand, Swift allows you to create functions, which let you combine several instructions together and execute them by calling a single name. You can also create closures, which let you combine several instructions together without a name and assign them to a constant or variable.

By the end of this chapter, you’ll have learned about functions, nested functions, functions as return types, functions as arguments, and the guard statement. You’ll also have learned how to create and use closures.

The following topics will be covered in this chapter:

  • Exploring functions
  • Exploring closures

Technical requirements

The Xcode playground for this chapter is in the Chapter06 folder of the code bundle for this book, which can be downloaded here:

https://github.com/PacktPublishing/iOS-17-Programming-for-Beginners-Eighth-Edition

Check out the following video to see the code in action:

https://youtu.be/H9KeyLWJwTU

If you wish to start from scratch, create a new playground and name it FunctionsAndClosures.

You can type in and run all the code in this chapter as you go along. Let’s start by learning about functions.

Exploring functions

Functions are useful for encapsulating several instructions that collectively perform a specific task, for example:

  • Calculating the 10% service charge for a meal at a restaurant
  • Calculating the monthly payment for a car that you wish to purchase

Here’s what a function looks like:

func functionName(parameter1: ParameterType, ...) -> ReturnType {
   code
}

Every function has a descriptive name. You can define one or more values that the function takes as input, known as parameters. You can also define what the function will output when done, known as its return type. Both parameters and return types are optional.

You “call” a function’s name to execute it. This is what a function call looks like:

functionName(parameter1: argument1, )

You provide input values (known as arguments) that match the type of the function’s parameters.

To learn more about functions, visit...

Exploring closures

A closure, like a function, contains a sequence of instructions and can take arguments and return values. However, closures don’t have names. The sequence of instructions in a closure is surrounded by curly braces ({ }), and the in keyword separates the arguments and return type from the closure body.

Closures can be assigned to a constant or variable, so they’re handy if you need to pass them around inside your program. For instance, let’s say you have an app that downloads a file from the internet, and you need to do something to the file once it has finished downloading. You can put a list of instructions to process the file inside a closure and have your program execute it once the file finishes downloading.

You’ll now write a closure that applies a calculation on each element of an...

Summary

In this chapter, you studied how to group statements together into functions. You learned how to use custom argument labels, functions inside other functions, functions as return types, functions as parameters, and the guard statement. This will be useful later when you need to accomplish the same task at different points in your program.

You also learned how to create closures. This will be useful when you need to pass around blocks of code within your program.

In the next chapter, we will study classes, structures, and enumerations. Classes and structures allow for the creation of complex objects that can store state and behavior, and enumerations can be used to limit the values that can be assigned to a variable or constant, reducing the chances of error.

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
iOS 17 Programming for Beginners - Eighth Edition
Published in: Oct 2023Publisher: PacktISBN-13: 9781837630561
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Ahmad Sahar

Ahmad Sahar is a trainer, presenter, and consultant at Tomafuwi Productions, specializing in conducting training courses for macOS and iOS, macOS Support Essentials certification courses, and iOS Development courses. He is a member of the DevCon iOS and MyCocoaHeads online communities in Malaysia and has conducted presentations and talks for both groups. In his spare time, he likes building and programming LEGO Mindstorms robots.
Read more about Ahmad Sahar