What if your functions could guess missing information and still work perfectly?
Why Default parameter values in Swift? - Purpose & Use Cases
Imagine you are writing a function to greet people. Sometimes you want to say "Hello, John!" and other times just "Hello!" without a name. Without default values, you must write two separate functions or always provide a name, even if you don't have one.
This manual way is slow and clumsy. You repeat code or force users to give extra information. It's easy to make mistakes or forget to handle cases where no name is given. This makes your code messy and harder to maintain.
Default parameter values let you set a standard value for a function's input. If no value is given, the function uses the default automatically. This keeps your code clean, simple, and flexible without extra effort.
func greet(name: String) {
print("Hello, \(name)!")
}
// Must always call greet(name: "John")func greet(name: String = "") { if name.isEmpty { print("Hello!") } else { print("Hello, \(name)!") } } // Can call greet() or greet(name: "John")
You can write simpler functions that work well in many situations without extra code or confusion.
Think about a coffee order app where the user can choose a size but if they don't, the app automatically picks a medium size. Default values make this easy and smooth.
Default values reduce repeated code and errors.
They make functions easier to use and more flexible.
They help keep your code clean and simple.