External Parameter Names in Swift
External Parameter Names in Swift
In Swift, functions can have external parameter names, which are the names used when calling the function. These external names make function calls more readable and expressive by describing the purpose of each argument.
What are External Parameter Names?
• External Parameter Names are names explicitly declared for function parameters to be used when calling the function.
• They are different from internal parameter names, which are used inside the function’s body.
Why Use External Parameter Names?
1. Improves Readability: Function calls become more descriptive.
2. Clarifies Arguments: Helps other developers understand the purpose of each argument without needing to inspect the function definition.
3. Enhances Code Quality: Functions are self-documenting when called.
Syntax
When defining a function, you can specify both external and internal parameter names:
func functionName(externalName internalName: Type) {
// Function body using internalName
}
• externalName: Used when calling the function.
• internalName: Used within the function body.
Examples and Progression (Easy to Advanced)
Level 1: External and Internal Names
Example: Using Different External and Internal Names
func greet(user name: String) {
print("Hello, \(name)!")
}
// Calling the function
greet(user: "Alice")
// Output:
// Hello, Alice!
Explanation:
• user is the external name used during the function call.
• name is the internal name used within the function.
Level 2: Omitting External Names with _
You can omit the external parameter name by using _ as the external name.
Example: Function Without External Names
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}
// Calling the function
let result = multiply(4, 5)
print("Result: \(result)")
// Output:
// Result: 20
Explanation:
• _ indicates that the parameter does not require an external name when calling the function.
Level 3: Mixing External and Internal Names
A function can have a mix of parameters with and without external names.
Example: Descriptive External Names
func calculateArea(ofLength length: Int, andWidth width: Int) -> Int {
return length * width
}
// Calling the function
let area = calculateArea(ofLength: 10, andWidth: 5)
print("Area: \(area)")
// Output:
// Area: 50
Explanation:
• ofLength and andWidth are external names that make the function call descriptive.
• length and width are internal names used within the function body.
Level 4: Using Default External Names
By default, Swift automatically uses the parameter names as their external names if no external name is specified.
Example: Default External Names
func subtract(from minuend: Int, subtracting subtrahend: Int) -> Int {
return minuend - subtrahend
}
// Calling the function
let result = subtract(from: 10, subtracting: 4)
print("Result: \(result)")
// Output:
// Result: 6
Explanation:
• Since no external names were explicitly provided, the parameter names (from, subtracting) are used as their external names.
Level 5: Functions with Multiple External Names
You can specify external names for all parameters to make the function call more readable.
Example: Descriptive Function Calls
func travel(to destination: String, by vehicle: String, at time: String) {
print("Traveling to \(destination) by \(vehicle) at \(time).")
}
// Calling the function
travel(to: "Paris", by: "Train", at: "10:00 AM")
// Output:
// Traveling to Paris by Train at 10:00 AM.
Explanation:
• to, by, and at are external names, making the function call easy to understand.
• The function clearly describes each argument during the call.
Level 6: Using Default Values with External Names
External parameter names can be combined with default parameter values.
Example: Function with Defaults
func placeOrder(for item: String, quantity: Int = 1) {
print("Order placed for \(quantity) \(item)(s).")
}
// Calling the function with and without the second parameter
placeOrder(for: "Pizza") // Output: Order placed for 1 Pizza(s).
placeOrder(for: "Burger", quantity: 3) // Output: Order placed for 3 Burger(s).
Explanation:
• for is the external name for the item parameter.
• The quantity parameter has a default value of 1, so it’s optional during the call.
Best Practices for Using External Parameter Names
1. Use Descriptive Names:
• Choose external names that clearly indicate the purpose of the parameter.
• Example: Use ofLength instead of a generic name like length.
2. Omit When Unnecessary:
• Use _ to omit external names when they don’t improve readability.
• Example: A multiply function doesn’t need external names for a and b.
3. Leverage Default External Names:
• Swift automatically uses parameter names as external names, so rely on this feature when it aligns with your design.
4. Improve Function Call Readability:
• External names should make the function call self-explanatory without requiring knowledge of the function’s implementation.
Common Use Cases for External Parameter Names
1. Describing Input Context:
func pay(amount: Double, withMethod method: String) {
print("Paying \(amount) using \(method).")
}
pay(amount: 100.0, withMethod: "Credit Card")
2. Clarifying Action:
func compare(value first: Int, to second: Int) -> Bool {
return first == second
}
compare(value: 5, to: 10)
3. Avoiding Ambiguity:
func move(from start: String, to end: String) {
print("Moving from \(start) to \(end).")
}
move(from: "A", to: "B")
Advanced Example: External Names in Closures
External names can also be used in functions that accept closures.
Example: Sorting with External Names
func sortNumbers(_ numbers: [Int], by order: (Int, Int) -> Bool) -> [Int] {
return numbers.sorted(by: order)
}
let ascendingOrder = sortNumbers([5, 3, 8, 1], by: { $0 < $1 })
print(ascendingOrder)
// Output: [1, 3, 5, 8]
Comments
Post a Comment