Swift Basics: [Advanced - Functions] Default Parameters & Argument Labels
⚙️ Default Parameter Values
A default parameter value allows a parameter to automatically assume a specific value if no argument is passed in when the function is called.
To declare a default parameter, simply specify the type after the parameter name and assign the default value to it. Tip: It is highly recommended to place parameters with default values at the very end of your parameter list.
// Specify the type after the parameter name and assign the default value
func functionName(param1Name: Param1Type, param2Name: Param2Type = DefaultValue...) -> ReturnType {
// Function implementation
return returnValue
}
Let's look at an example. Below, we've set the default parameter value for me to "Jeamin".
// A default value is assigned after the 'me: String' parameter type
func greeting(friend: String, me: String = "Jeamin") {
print("Hello \(friend)! I am \(me).")
}
Now let's call the function. Because we set a default value, you can see that the function works perfectly even if we don't explicitly provide a value for me. If you want to override the default value, you simply state the me parameter and pass in your new value.
// Parameters with default values can be safely omitted
greeting(friend: "Kiki") // Hello Kiki! I am Jeamin.
greeting(friend: "Ponyo", me: "Howl") // Hello Ponyo! I am Howl.
🏷️ Argument Labels
Argument labels are heavily used in Swift to make the role of a parameter explicitly clear when calling a function. They make your code read much more naturally, almost like an English sentence.
// Add the 'argument label' right before the parameter name
func functionName(argumentLabel param1Name: Param1Type, argumentLabel param2Name: Param2Type...) -> ReturnType {
// Function implementation
return returnValue
}
Inside the function's body, you still use the parameter name. Outside the function (when calling it), you use the argument label.
Using argument labels also makes function overloading very easy.
Wait, we already defined a greeting function above—can we use the same name again? Yes, we can!
While it looks like we are using the exact same greeting function, Swift actually treats the argument labels as part of the function's full signature. So, to Swift, greeting(friend:me:) and greeting(to:from:) are recognized as two completely different functions.
// Here, we added the argument labels 'to' and 'from'
func greeting(to friend: String, from me: String) {
print("Hello \(friend)! I am \(me).")
}
greeting(to: "Howl", from: "Jeamin") // Hello Howl! I am Jeamin.
댓글
댓글 쓰기