Lesson 36Functions
Variadic Parameters
Accept Any Number of Values
Variadic parameters let your function accept zero or more values of a specific type. Use three dots (...) after the type!
Syntax
func sum(_ numbers: Int...) -> Int
How It Works
When Calling
Pass values separated by commas
sum(1, 2, 3, 4, 5)Inside Function
Treated as an array
numbers: [Int]Rules
- Only ONE variadic parameter per function
- Must come after regular parameters
- Can have parameters after it (with labels)
- Empty calls are allowed (0 values)
Common Use Cases
sum()average()print()max()log()
main.swift
// VARIADIC PARAMETERS
// Accept any number of values of the same type
func sum(_ numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
// Call with different amounts
print(sum(1, 2, 3)) // 6
print(sum(1, 2, 3, 4, 5)) // 15
print(sum(10)) // 10
print(sum()) // 0 (empty is allowed)
// Inside the function, numbers is an [Int] array!
// PRACTICAL EXAMPLES
// 1. Print multiple items
func printAll(_ items: Any...) {
for item in items {
print(item)
}
}
printAll("Hello", 42, true, 3.14)
// 2. Find average
func average(_ numbers: Double...) -> Double {
guard !numbers.isEmpty else { return 0 }
let sum = numbers.reduce(0, +)
return sum / Double(numbers.count)
}
print(average(85, 90, 78, 92)) // 86.25
// 3. Build HTML class string
func classes(_ names: String...) -> String {
return names.joined(separator: " ")
}
print(classes("btn", "btn-primary", "active"))
// "btn btn-primary active"
// COMBINING WITH OTHER PARAMETERS
// Variadic must come after regular parameters
func greet(title: String, names: String...) {
for name in names {
print("\(title) \(name)")
}
}
greet(title: "Hello", names: "Alice", "Bob", "Charlie")
// WITH DEFAULT PARAMETERS
func log(level: String = "INFO", messages: String...) {
for msg in messages {
print("[\(level)] \(msg)")
}
}
log(messages: "App started", "Loading data")
log(level: "ERROR", messages: "Failed to connect")
// LIMITATIONS
// Only one variadic parameter per function
// Variadic parameter is treated as an array inside
// REAL-WORLD: Custom print function
func debugLog(_ items: Any..., separator: String = " ") {
let output = items.map { String(describing: $0) }
print("[DEBUG]", output.joined(separator: separator))
}
debugLog("User:", "Alice", "Age:", 25)Try It Yourself!
Create a function `max(_ values: Int...)` that returns the largest number from any amount of inputs!