Lesson 31Functions
Function Basics
What are Functions?
Functions are reusable blocks of code that perform specific tasks. Think of them as recipes - you write them once and can use them over and over!
Function Anatomy
func functionName(parameter: Type) -> ReturnType {
// code here
return value
}
// code here
return value
}
Function Types
No Parameters, No Return
func sayHi() { }With Parameters
func greet(name: String) { }With Return Value
func add(a: Int, b: Int) -> IntBoth
Full function with all partsWhy Use Functions?
- DRY - Don't Repeat Yourself
- Readable - Code is easier to understand
- Reusable - Use the same code everywhere
- Testable - Easy to find and fix bugs
main.swift
// What is a Function?
// A reusable block of code that performs a specific task
// DEFINING A FUNCTION
func sayHello() {
print("Hello, World!")
}
// CALLING A FUNCTION
sayHello() // Output: Hello, World!
sayHello() // Can call as many times as needed!
// FUNCTION WITH A PARAMETER
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "Alice") // Hello, Alice!
greet(name: "Bob") // Hello, Bob!
// FUNCTION WITH MULTIPLE PARAMETERS
func introduce(name: String, age: Int) {
print("Hi, I'm \(name) and I'm \(age) years old.")
}
introduce(name: "Charlie", age: 12)
// FUNCTION WITH RETURN VALUE
func add(a: Int, b: Int) -> Int {
return a + b
}
let sum = add(a: 5, b: 3)
print("Sum: \(sum)") // Sum: 8
// Use the result directly
print(add(a: 10, b: 20)) // 30
// SINGLE EXPRESSION FUNCTIONS
// If the function has only one line, you can omit 'return'
func multiply(a: Int, b: Int) -> Int {
a * b // Implicit return
}
print(multiply(a: 4, b: 5)) // 20
// WHY USE FUNCTIONS?
// 1. Avoid repeating code (DRY - Don't Repeat Yourself)
// 2. Make code easier to read and understand
// 3. Easy to test and fix bugs
// 4. Can reuse in different parts of your programTry It Yourself!
Create a function called `calculateArea` that takes width and height as parameters and returns the area of a rectangle!