Default parameter values
Optional parameters on functions and inits.
Default parameter values
Optional parameters on functions and inits.
0
0
Checkbox to mark video as read
Mark as read

In Swift, you can provide default values for function and inittializers parameters. This allows you to call a function or init without explicitly passing arguments for every parameter. If a parameter is omitted in a function call, its default value will be used.

Defining Default Values

To assign a default value to a parameter, simply set the value when declaring the parameter in the function signature.

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

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

In the example above, the greet() function has a default value of "Guest" for the name parameter. If no argument is provided, the default value will be used.

Multiple Default Values

You can provide default values for multiple parameters, making it flexible to call the function with or without arguments.

func printMessage(message: String = "Hello", times: Int = 1) {
    for _ in 0..<times {
        print(message)
    }
}

printMessage()               // Output: "Hello"
printMessage(message: "Hi")  // Output: "Hi"
printMessage(times: 3)       // Output: "Hello" (3 times)

Here, both message and times have default values, allowing for different combinations of arguments when calling printMessage().

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy