Function Basics
A function is a named recipe of steps you can run whenever you want, just by calling its name.
Syntax
func functionName(paramName: Type) -> ReturnType {
return value
}
func functionName() { // no return value
}
functionName(paramName: value)
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
// Define the function `greet` taking `name` and returning a String
func greet(name: String) -> String {
// Return `"Hello, \(name)!"` from this function
return "Hello, \(name)!"
}
// Print `greet(name: "Swift")` to the console
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
// Define the function `printBanner` taking `title`
func printBanner(title: String) {
// Print "=== \(title) ===" to the console
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
// Define the function `add` taking `a`, `b` and returning an Int
func add(a: Int, b: Int) -> Int {
// Return `a + b` from this function
return a + b
}
// Print `add(a: 3, b: 4)` to the console
print(add(a: 3, b: 4))
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: