Functions: name reusable work
Functions: name reusable work
A report calculation should not be copied for every student. A function groups statements behind a name, accepts inputs and can return a result. Its parameter types and return type make the contract visible before you inspect its body.
What you’ll learn
- Call a typed function and use its return value.
- Identify the missing zero-count validation in an average calculation.
Functions: name reusable work in the example
Call with inputs
A report calculation should not be copied for every student.
Call with inputsCompute a result
The func keyword begins a declaration.
Compute a resultReturn to caller
The caller supplies total 155 and count 2 using labels.
Return to caller
How functions: name reusable work works
The func keyword begins a declaration. Parameters receive values for each call, and an arrow names the return type. A local constant exists inside that call’s scope. Returning a value differs from printing it: callers can use a returned number in later calculations.
Work through functions: name reusable work
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
func average(total: Int, count: Int) -> Double {
return Double(total) / Double(count)
}
let result = average(total: 155, count: 2)
print(result)Expected output
77.5Follow the execution
The caller supplies total 155 and count 2 using labels. The function converts both integers and returns 77.5. Assigning that result keeps it available to the caller; the print happens separately afterward.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Functions: name reusable work
Your task: What input must this simple function reject before division?
Swift · complete program
func average(total: Int, count: Int) -> Double {
return Double(total) / Double(count)
}
let result = average(total: 155, count: 2)
print(result)Worked answer
It must reject a count of zero for a meaningful average. Add validation or a suitable optional or throwing result, rather than presenting division by zero as a valid report.
Return a value the caller can use
A function body can contain branches, loops and other calls. Scope prevents a local name from automatically becoming available everywhere. Avoid recursion without a stopping case, because repeatedly calling the same function can exhaust resources.
Check your decision
Return a value the caller can use
It must reject a count of zero for a meaningful average. Add validation or a suitable optional or throwing result, rather than presenting division by zero as a valid report. A function body can contain branches, loops and other calls.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.