Module 6: Functions in Swift
Functions are reusable blocks of code that perform specific tasks. In Swift, functions help you organize your code into manageable, logical parts. They can accept input parameters and return values, making your code modular and efficient.
Defining and Calling Functions
You define a function using the func
keyword, followed by the function name and parentheses. Inside the parentheses, you specify parameters if needed.
func greet() {
print("Hello, Swift learner!")
}
greet() // Calling the function
Functions with Parameters
Functions can accept input parameters to perform tasks with different values.
func greet(name: String) {
print("Hello, \(name)!")
}
greet(name: "Alice")
Functions with Return Values
Functions can return values using the ->
syntax.
func add(a: Int, b: Int) -> Int {
return a + b
}
let sum = add(a: 5, b: 3)
print(sum) // Output: 8
Parameter Labels and Omitting Labels
Swift allows external parameter labels for clarity when calling functions.
func greet(person name: String) {
print("Hello, \(name)!")
}
greet(person: "Bob")
To omit labels, use an underscore _
:
func greet(_ name: String) {
print("Hello, \(name)!")
}
greet("Charlie")
Functions with Multiple Return Values
Use tuples to return multiple values from a function.
func getMinMax(numbers: [Int]) -> (min: Int, max: Int)? {
guard let first = numbers.first else { return nil }
var min = first
var max = first
for number in numbers {
if number < min { min = number } else if number > max {
max = number
}
}
return (min, max)
}
if let result = getMinMax(numbers: [3, 7, 2, 9, 5]) {
print("Min: \(result.min), Max: \(result.max)")
}
Nested Functions
Functions can be defined inside other functions for encapsulation.
func outer() {
func inner() {
print("Inner function called")
}
inner()
}
outer()
Functions as First-Class Citizens
Functions can be assigned to variables and passed as arguments.
func square(number: Int) -> Int {
return number * number
}
let myFunc = square
print(myFunc(4)) // Output: 16
Summary
- Functions help organize reusable code blocks.
- Functions can take parameters and return values.
- Parameter labels improve readability.
- Functions can return multiple values using tuples.
- Nested functions and function variables increase flexibility.