Function Basics
A function is a named recipe of steps you can run whenever you want, just by calling its name.
Declaring and Calling a Function
A function is defined with func, a name, parameters in parentheses, and an optional return type after ->.
Example: Declaring and Calling a Function
func greet(name: String) -> String {
return "Hello, \(name)!"
}
print(greet(name: "Swift"))
Login to try C/C++/Java/PHP code in the editor
Functions Without a Return Value
A function that only performs an action, without producing a value, simply omits the -> return type entirely.
Example: Functions Without a Return Value
func printBanner(title: String) {
print("=== \(title) ===")
}
printBanner(title: "Welcome")
Login to try C/C++/Java/PHP code in the editor
Multiple Parameters
A function can take several parameters, each with its own name and type, separated by commas.
Example: Multiple Parameters
func add(a: Int, b: Int) -> Int {
return a + b
}
print(add(a: 3, b: 4))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the
->arrow before the return type, writingfunc add(a: Int, b: Int) Intinstead offunc add(a: Int, b: Int) -> Int. - Omitting
returninside a multi-statement function body; only single-expression bodies can skip it implicitly. - Calling a function without its argument labels when they are required, e.g. calling
add(a, b)instead ofadd(a: a, b: b).
Chapter Summary
- Functions are declared with
func name(parameters) -> ReturnType { }. - Parameters and their types are listed in parentheses, separated by commas.
- A function with no meaningful return value omits the
-> ReturnTypepart (implicitly returningVoid). - Calling a function uses its name followed by arguments in parentheses, using labels by default.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: