Main image of article Swift Tutorial: Getting Started with Functions

If you’re learning Swift, Apple’s new(ish) language for iOS and macOS development, trust us when we tell you that functions are about to become your best friend. Of all the topics we’ve covered in recent Swift tutorials, including arrayssets, and strings, functions are among the most powerful and dynamic tools at your disposal.

But what is a function, and why are they so effective for Swift coding? Let’s get to it!

What’s a Function in Swift?

Here’s the simplest way to define a function: It’s a wrapper for complex snippets of code. It’s handy for those times you need to do a thing multiple times within your codebase, or perform a task multiple times.

And if you’re thinking “Hey, that sounds like loops!”… well, you’re not wrong. And you can use a loop within a function if you wish (or replace a loop with a function). 

Functions allow you to wrap complex code up so you can use it throughout your code. Let’s say you wrote a really complex ‘while’ loop and thought, “Okay, great, I’ve got that bit handled,” but then figured out you’d need to use that exact same loop elsewhere in your code. You could copy-paste, but that’s redundant, and renders it really hard to make changes later if you need to.

A better way: Adding that loop into a function, then calling that function throughout your code. Functions keep things clean and nimble. That’s why everyone loves them!

Breaking Down a Swift Function

A Swift function looks like this:

func name() -> Value { code return }

You initialize it with the func keyword, then name it. The parameters – () – can be empty or hold value, but we’ll get to that later. For now, just know you need to have them no matter what.

The arrow points to a return value. As you see in the code, functions need a return statement, and pointing to a return value narrows what can be returned, such as String or Int. You don’t need to have a return value, but it can be handy if you’re specifically trying to return a specific value type.

Code is the core of any function; it can be just about anything you want. 

Every function has a return statement. You don’t have to specify the return value, but you do need a return statement. This is like a print statement, only it shows in an app, not just the Xcode console.

Swift Functions: Basics

Let’s go back to our Swift arrays article, where we had three names:

let names = [“Nate”, “Nick”, “Neil”]

In that article, we pointed out how you could use the array to greet each person as they arrived at an event. However, it would only print to a console. What if you wanted the system to be fully automated, and display their greeting on a screen?

You could use a function for something like that! Here’s an example:

func greet(person: String) -> String { let greeting = “Hey, ” + person “, welcome to the event!” return greeting }

Now, any time someone entered their name, a screen could show something like, “Hey, Nate, welcome to the event!” In your codebase, you could simply call the greeting function instead of entering this code multiple times. If they were returning to the event, you could write a simpler function welcoming them back:

func returnGuest(person: String) -> String { return "Welcome back, " + person }

Functions are extensible, and almost limitless. Let’s expand on the above function just a bit, and add an “if-else” statement for someone who may have already checked in:

func finalGreeting(person: String, alreadyGreeted: Bool) -> String { if alreadyGreeted { return returnGuest(person: person) } else { return greet(person: person) } }

Now you have three functions: One for a first-time attendee, one for a returning guest, and one broader function that checks to see if they’ve checked in (and how to greet them).

We can see here that we’ve passed multiple arguments through our parameters for the finalGreeting function, too. It allows us to monitor for both the person’s name and whether they’ve checked in.

Why Use Functions?

Let’s consider that, at our event, you can come and go through the front door as you please, which is where the above “big” function comes into play. If you’re a first-timer, it says “welcome,” and if you’re returning, it says, “welcome back!”

You may be wondering why the “welcome” and “welcome back” messages need to be functions at all. Well, let’s assume there are sessions at this event, and attendees can’t come and go as they please in those rooms. There’s no need for a “welcome back” message, but the “welcome” message can be used more globally.

There is broad appeal for using functions. Temporary power-ups in games can be held as functions, for example, as can simpler items such as animations for dismissing notifications or loading screens.

Conclusion

We’ve gone through the basic use of functions, but this just scratches the surface. It’s best to get a strong grasp of what functions can do before we dive deeper.

We encourage you to tinker with functions in an Xcode playground. Come up with a few small projects you think would be useful as functions, then see how clever you can be!