Lesson 35Functions

Default Parameters

Default Parameter Values

Default parameters let you set fallback values. Callers can skip these parameters and use the defaults, or provide their own values!

Syntax

func greet(name: String = "Guest") { }

Benefits

Flexibility

Call with some, all, or no optional params

Cleaner Calls

Only specify what you need to change

Less Overloading

One function instead of many versions

Self-Documenting

Default values show common usage

Best Practices

  • Put required parameters first, then optional ones
  • Use sensible defaults that work for most cases
  • Don't make required data optional with defaults
  • Consider using defaults instead of function overloads
main.swift
// DEFAULT PARAMETER VALUES
// Provide a fallback value if caller doesn't specify

func greet(name: String = "Guest") {
    print("Hello, \(name)!")
}

greet()              // Hello, Guest!
greet(name: "Alice") // Hello, Alice!

// MULTIPLE DEFAULT PARAMETERS
func createUser(
    name: String,
    age: Int = 0,
    country: String = "Unknown",
    isAdmin: Bool = false
) {
    print("Name: \(name)")
    print("Age: \(age)")
    print("Country: \(country)")
    print("Admin: \(isAdmin)")
}

// Call with all defaults
createUser(name: "Bob")

// Override some defaults
createUser(name: "Charlie", age: 25)
createUser(name: "David", country: "USA")
createUser(name: "Eve", isAdmin: true)

// Override all
createUser(name: "Frank", age: 30, country: "UK", isAdmin: true)

// PRACTICAL EXAMPLES

// 1. HTTP Request with defaults
func request(
    url: String,
    method: String = "GET",
    timeout: Int = 30
) {
    print("\(method) \(url) (timeout: \(timeout)s)")
}

request(url: "https://api.example.com")
request(url: "https://api.example.com", method: "POST")
request(url: "https://api.example.com", method: "PUT", timeout: 60)

// 2. Print with separator
func printItems(_ items: String..., separator: String = ", ") {
    print(items.joined(separator: separator))
}

printItems("Apple", "Banana", "Cherry")
printItems("A", "B", "C", separator: " - ")

// 3. Game settings
func startGame(
    difficulty: String = "Normal",
    players: Int = 1,
    soundEnabled: Bool = true
) {
    print("Starting \(difficulty) game with \(players) player(s)")
    print("Sound: \(soundEnabled ? "ON" : "OFF")")
}

startGame()
startGame(difficulty: "Hard")
startGame(difficulty: "Easy", players: 2, soundEnabled: false)

// DEFAULT VALUES EVALUATED AT CALL TIME
var counter = 0
func getNextID(prefix: String = "ID-\(counter)") -> String {
    counter += 1
    return prefix
}

Try It Yourself!

Create a function `formatPrice(amount: Double, currency: String = "$", decimals: Int = 2)` that formats prices!