Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Functions  ›  Lesson

Basic Functions

Basic Functions 12 minA function names a block of code with func so it can be called by name with brackets, taking parameters and optionally returning a value.

Basic Functions

Sprout builds the same streak message on the home screen, in the weekly summary and in a notification. Copying those lines into three places means three places to fix when the wording changes. A function names the job once so every screen can ask for it.

The rule

Name a job once with func; run it by name with brackets.

The simplest function takes nothing and gives nothing back:

func sayWelcome() {
    print("Welcome back to Sprout 🌱")
}

sayWelcome()      // runs the body
sayWelcome()      // and again, as often as you like

The parts:

  • func starts the definition.
  • The name, in camelCase, usually a verb: sayWelcome, markDone, resetStreak.
  • Brackets () hold the inputs, here none.
  • The body in braces is the code that runs on each call.

Most functions take an input and hand back a result:

func streakMessage(days: Int) -> String {
    return "You're on a \(days)-day streak"
}

let text = streakMessage(days: 5)   // "You're on a 5-day streak"

days: Int is a parameter, the input's name and type. -> String says what comes back, and return sends it. When the whole body is one expression, you may leave out return:

func streakMessage(days: Int) -> String {
    "You're on a \(days)-day streak"
}

Defining a function does not run it. Nothing happens until you call it, and writing the name without brackets, sayWelcome, does not call it either.

The shortcut

When you see a call, replace it in your head with the body, with each parameter swapped for the value passed in. When you see repeated lines, ask "what differs between the copies?" That difference becomes the parameter; the rest becomes the body.

Turning Sprout's copies into one functionStep 1 of 4
  1. Spot the repeats

    Home: "You're on a 3-day streak". Summary: "You're on a 12-day streak". Only the number changes.

Drills

Answer fast — trust the rule.

quick drill

What happens when Swift reaches the line func sayWelcome() { print("Hi") }?

quick drill

How do you run a function named resetStreak that takes no inputs?

quick drill

What does streakMessage(days: 1) return?

quick drill

Which function body may leave out the word return?

Remember

  • Name a job once with func; run it by name with brackets.
  • Repeated code: what differs becomes the parameter, the rest the body.
  • Defining is not calling; single-expression bodies can skip return.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainExtract a function

Sprout builds the text 'Read: 3 of 5 done' in three places with different habits and numbers. Explain how you would turn this into one function: its name, parameters, return type and how each place would call it.