Chapter 4. Functions and Enums: Reusing Code on Demand
Functions in Swift allow you to package up a specific behavior or unit of work into a single block of code that you can call from other parts of your program. Functions can be standalone, or they can be defined as part of a class, a structure, or an enumeration, where they are usually referred to as methods. Functions let you break down complex tasks into smaller, more manageable, and more testable units. They’re a core part of the way you structure a program with Swift.
Functions in Swift let you reuse code
Like many programming languages, Swift has a feature known as functions. Functions let you package up some code, and reuse it if you need to run it more than once.
We’ve been using functions a fair bit already: the print function, for example, is a built-in function that lets us print things for display. Swift has lots of other built-in functions, and you’ll get a chance to use some of them in a moment.
What can functions do?
Functions can, in no particular order, do all sorts of things, including:
Note
Including, but not limited to!
Be defined as a block of code that just does something, and doesn’t need any ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access