Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Default Parameter Values in Swift
Written by Team Kodeco

When declaring a function, you can provide default values for its parameters. This means that if a value isn’t passed for that parameter when the function is called, the default value will be used instead. This can be useful for parameters that often have the same value and can save the caller from having to always pass that value.

Here is an example of a function that has a default parameter value:

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

In this example, the message parameter has a default value of “Hello”. When the function is called, if a value for message isn’t provided, the default value will be used.

greet(name: "John") // prints "Hello John!"
greet(name: "Jane", message: "Hi") // prints "Hi Jane!"

You can also use default parameter values in conjunction with external parameter names.

func greet(name: String, with message: String = "Hello") {
    print("\(message) \(name)!")
}
greet(name: "John") // prints "Hello John!
greet(name: "Jane", with: "Hi") // prints "Hi Jane!"

In this example, the external parameter name is “with” and the default parameter value is “Hello”. This can make the function call more readable.

Note: Default parameter values aren’t available for variadic parameters or inout parameters.

© 2024 Kodeco Inc.