Default Values
Part of the Fundamentals section of Coddy's Swift journey — lesson 57 of 86.
Sometimes a parameter has a value that's used most of the time. Instead of requiring the caller to provide it every time, you can assign a default value to that parameter.
To set a default value, use the assignment operator (=) after the parameter's type:
func greet(name: String, greeting: String = "Hello") {
print("\(greeting), \(name)!")
}
greet(name: "Alice") // Output: Hello, Alice!
greet(name: "Bob", greeting: "Hi") // Output: Hi, Bob!When calling the function, you can omit parameters that have default values. Swift will use the default automatically. But if you need a different value, you can still provide one explicitly.
Parameters with default values should be placed at the end of the parameter list. This keeps function calls clean and readable:
func calculatePrice(base: Double, taxRate: Double = 0.1) -> Double {
return base + (base * taxRate)
}
print(calculatePrice(base: 100)) // Output: 110.0
print(calculatePrice(base: 100, taxRate: 0.2)) // Output: 120.0Default values make your functions more flexible—they work simply for common cases while still allowing customization when needed.
Challenge
EasyWrite a function formatGreeting that takes name, greeting, and repeatCount and returns a formatted greeting message.
The function should use default values for the optional parameters:
greetingshould default to"Hello"repeatCountshould default to1
Build a string that repeats the greeting pattern the specified number of times, separated by spaces.
Parameters:
name(String): The person's name (required)greeting(String): The greeting word (default:"Hello")repeatCount(Int): How many times to repeat the greeting (default:1)
Returns: A string with the greeting pattern repeated. Format: "[greeting], [name]!" repeated repeatCount times, separated by a single space (String)
For example, if name is "Alice", greeting is "Hi", and repeatCount is 2, the function returns "Hi, Alice! Hi, Alice!".
If called with just name as "Bob" (using defaults), it returns "Hello, Bob!".
Cheat sheet
To set a default value for a parameter, use the assignment operator (=) after the parameter's type:
func greet(name: String, greeting: String = "Hello") {
print("\(greeting), \(name)!")
}
greet(name: "Alice") // Output: Hello, Alice!
greet(name: "Bob", greeting: "Hi") // Output: Hi, Bob!When calling a function, you can omit parameters that have default values. Swift will use the default automatically, but you can still provide a different value explicitly if needed.
Parameters with default values should be placed at the end of the parameter list:
func calculatePrice(base: Double, taxRate: Double = 0.1) -> Double {
return base + (base * taxRate)
}
print(calculatePrice(base: 100)) // Output: 110.0
print(calculatePrice(base: 100, taxRate: 0.2)) // Output: 120.0Try it yourself
func formatGreeting(name: String, greeting: String, repeatCount: Int) -> String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input