Chapter    28

Nested Functions

You can code functions within other functions. Nesting functions gives you a way to organize and reuse your code while limiting the scope of functions to the parent function.

For instance, let’s say you wanted to write a Swift program to help a teacher summarize how some students performed on the tests they took this week. You could write a function called analyzeTestScores() that would figure out what the average score of a test was including all students and then would write a report.

Since this function has to do a few things, it makes sense to organize each task into separate functions. You could start by adding a function that returns the average test score based on an array of numbers (see Listing 28-1). ...

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.