https://useyourloaf.com/blog/swift-named-parameters/
Local parameter names are used in the body of the function/method
External parameter names are used when calling the function/method.
The external names for all except the first parameter default to the local name
1 2 3 |
func myFunc(userName name: String, age: Int) -> Void { } |
When we call myFunc, we’d do it like:
1 |
myFunc(userName: "ricky" age: 36) |
As you can see, when calling the function, we use the param names userName. However, for 2nd parameter and on, the external name is the same as local name.
You omit the name of the first parameter when calling the function/method (since it does not by default have an external name)
1 2 3 4 5 |
func logMessage(message: String, prefix: String, suffix: String) { print("\(prefix)-\(message)-\(suffix)") } logMessage("error message", prefix: ">>>", suffix: "<<<") |
Using External Names
If you rather define your own external names, and not use the local names, you can do so also. Just define your external name in front of the local name
1 2 3 4 5 6 7 |
func logMessage(message message:String, withPrefix prefix: NSString, andSuffix suffix: NSString) { print("\(prefix)-\(message)-\(suffix)") } logMessage(message: "QWERTY", withPrefix: "***", andSuffix: "$$$") |
Our three parameters now have these external and local names:
external: message, local: message
external: withPrefix, local: prefix
external: andSuffix, local: suffix
The use of external parameter names can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent.