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 likeThe parts:
funcstarts 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.
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.
What happens when Swift reaches the line func sayWelcome() { print("Hi") }?
How do you run a function named resetStreak that takes no inputs?
What does streakMessage(days: 1) return?
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.
