Skip to content

Swift Functions

New Course Coming Soon:

Get Really Good at Git

This tutorial belongs to the Swift series

Your program’s code is organized into functions.

A function is declared using the func keyword:

func bark() {
    print("woof!")
}

Functions can be assigned to structures, classes and enumerations, and in this case we call them methods.

A function is invoked using its name:

bark()

A function can return a value:

func bark() -> String {
    print("woof!")
	  return "barked successfully"
}

And you can assign it to a variable:

let result = bark()

A function can accept parameters. Each parameter has a name, and a type:

func bark(times: Int) {
    for index in 0..<times {
        print("woof!")
    }
}

The name of a parameter is internal to the function.

We use the name of the parameter when we call the function, to pass in its value:

bark(times: 3)

When we call the function we must pass all the parameters defined.

Here is a function that accepts multiple parameters:

func bark(times: Int, repeatBark: Bool) {
    for index in 0..<times {
        if repeatBark == true {
            print("woof woof!")
        } else {
            print("woof!")
        }            
    }
}

In this case you call it in this way:

bark(times: 3, repeat: true)

When we talk about this function, we don’t call it bark(). We call it bark(times:repeat:).

This is because we can have multiple functions with the same name, but different set of parameters.

You can avoid using labels by using the _ keyword:

func bark(_ times: Int, repeatBark: Bool) {
    //...the function body
}

So you can invoke it in this way:

bark(3, repeat: true)

It’s common in Swift and iOS APIs to have the first parameter with no label, and the other parameters labeled.

It makes for a nice and expressive API, when you design the names of the function and the parameters nicely.

You can only return one value from a function. If you need to return multiple values, it’s common to return a tuple:

func bark() -> (String, Int) {
    print("woof!")
	  return ("barked successfully", 1)
}

And you can assign the result to a tuple:

let (result, num) = bark()

print(result) //"barked successfully"
print(num) //1

Functions can be nested inside other functions. When this happens, the inner function is invisible to outside the outer function.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: