// Function without parameters and return value
func greet() {
print("Hello, world!")
}
// Function with parameters and return value
func addNumbers(_ a: Int, _ b: Int) -> Int {
let sum = a + b
return sum
}
// Function with external parameter names
func greet(person name: String, greeting: String = "Hello") {
print("\(greeting), \(name)!")
}
// Function with multiple return values using a tuple
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
let minScore = scores.min() ?? 0
let maxScore = scores.max() ?? 0
let sum = scores.reduce(0, +)
return (minScore, maxScore, sum)
}
// Example usage
greet()
let result = addNumbers(5, 3)
print("Sum: \(result)")
greet(person: "John", greeting: "Hi")
let stats = calculateStatistics(scores: [5, 3, 9, 2])
print("Min: \(stats.min), Max: \(stats.max), Sum: \(stats.sum)")
Here's a breakdown of the code:
Basic Function (greet):
- greet is a simple function without parameters and return value.
- It prints "Hello, world!" when called.
Function with Parameters and Return Value (addNumbers):
- addNumbers takes two parameters (a and b) and returns their sum as an Int.
- It uses the + operator to add the two numbers and then returns the result.
Function with External Parameter Names (greet):
- greet takes two parameters: name and greeting.
- greeting has a default value of "Hello".
- The function prints a greeting message with the provided name and greeting.
Function with Multiple Return Values (calculateStatistics):
- calculateStatistics takes an array of integers (scores) and returns a tuple with three values: minimum, maximum, and sum of the array elements.
- It uses optional chaining (??) to provide default values for min and max in case the array is empty.
Example Usage:
- The functions are then called with different arguments and their results are printed.
- When creating a function, consider whether it needs parameters, whether it returns a value, and how you want to name its parameters and return values. Swift allows for flexible and expressive function declarations to suit various needs.
0 Comments