Swift Variadic Parameters

Functions that accept multiple values

📦 What are Variadic Parameters?

Variadic parameters allow functions to accept zero or more values of the same type. Use three dots (...) after the parameter type to create flexible functions that work with varying numbers of arguments.


// Function that accepts multiple numbers
func sum(_ numbers: Int...) -> Int {
    var total = 0
    for number in numbers {
        total += number
    }
    return total
}

print(sum(1, 2, 3, 4, 5)) // Output: 15
                                    

Key Variadic Concepts

📝

Three Dots Syntax

Use ... after the type name

func greet(_ names: String...) {
    for name in names {
        print("Hello, \(name)!")
    }
}
🔢

Array-like Access

Variadic parameters become arrays inside functions

func count(_ items: String...) -> Int {
    return items.count
}

print(count("a", "b", "c")) // 3
🎯

Zero or More

Can accept zero or multiple values

func log(_ messages: String...) {
    if messages.isEmpty {
        print("No messages")
    }
}
⚠️

One Per Function

Only one variadic parameter per function

// ✅ Valid
func process(_ numbers: Int..., separator: String)

// ❌ Invalid - multiple variadic parameters

🔹 Basic Variadic Function

Here's a simple function that calculates the average of multiple numbers:

func average(_ numbers: Double...) -> Double {
    guard !numbers.isEmpty else { return 0 }
    
    let sum = numbers.reduce(0, +)
    return sum / Double(numbers.count)
}

print(average(10, 20, 30))        // 20.0
print(average(5, 15, 25, 35))     // 20.0
print(average())                  // 0.0

Output:

20.0

20.0

0.0

🔹 String Concatenation

Variadic parameters are perfect for joining multiple strings:

func joinWords(_ words: String..., separator: String = " ") -> String {
    return words.joined(separator: separator)
}

let sentence = joinWords("Swift", "is", "awesome")
let csvData = joinWords("Apple", "Banana", "Cherry", separator: ",")

print(sentence)  // Swift is awesome
print(csvData)   // Apple,Banana,Cherry

Output:

Swift is awesome

Apple,Banana,Cherry

🔹 Finding Maximum Value

Use variadic parameters to find the maximum among multiple values:

func findMax(_ numbers: Int...) -> Int? {
    guard !numbers.isEmpty else { return nil }
    
    var maximum = numbers[0]
    for number in numbers {
        if number > maximum {
            maximum = number
        }
    }
    return maximum
}

if let max = findMax(45, 23, 67, 12, 89, 34) {
    print("Maximum value: \(max)")
}

if let max = findMax(5) {
    print("Single value: \(max)")
}

Output:

Maximum value: 89

Single value: 5

🔹 Variadic with Other Parameters

Combine variadic parameters with regular parameters:

func formatList(title: String, _ items: String..., numbered: Bool = false) -> String {
    var result = "\(title):\n"
    
    for (index, item) in items.enumerated() {
        if numbered {
            result += "\(index + 1). \(item)\n"
        } else {
            result += "• \(item)\n"
        }
    }
    
    return result
}

let groceries = formatList(title: "Shopping List", "Milk", "Bread", "Eggs")
let tasks = formatList(title: "To Do", "Study Swift", "Write Code", "Test App", numbered: true)

print(groceries)
print(tasks)

Output:

Shopping List:
• Milk
• Bread
• Eggs

To Do:
1. Study Swift
2. Write Code
3. Test App

🔹 Best Practices

Follow these guidelines when using variadic parameters:

✅ Good Practices:

  • Use variadic parameters for functions that naturally work with multiple similar values
  • Handle empty parameter lists gracefully
  • Place variadic parameters before parameters with default values
  • Use meaningful parameter names

⚠️ Considerations:

  • Only one variadic parameter per function
  • Variadic parameters cannot have default values
  • Consider using arrays if you need to pass the values around

🧠 Test Your Knowledge

What syntax is used to create a variadic parameter?