External Parameter Names in Swift
I really like how Apple have implemented parameter names in Swift. In Objective-C you’re very much tied in to type out every parameter as they’re part of the method identifier. Methods are very verbose, and I have actually come to like that (from a C# background, it took some time to get used to at first).
In Swift, parameters have their internal name - i.e., what you call the parameter within the method itself. When calling the method, these names are optional. As the developer you could have a method such as:
func greet(name : String) -> String {
return “Hello, “ + name
}
Now call it with var greeting = greet(“Harry”)
. Very easy. Or you could force developers to specify the parameter name. In the previous example, this would be changed to:
func greet(name name : String) -> String
Which is essentially func greet(externalParameterName internalParameterName : String) -> String
.
Interestingly, if you set the external name to the same as the internal name, the compiler will warn you of this, and say you can make it look much better by simply giving the internal name a prefix of #
.
Sometimes you may also see the underscore (_
) character in Swift methods. When creating a method with a parameter that has a default value, Swift will automatically give it an external parameter name. You can override this behaviour by prefixing the parameter name with an underscore. For example:
func join(s1: String, s2: String, joiner: String = " ") -> String {
return s1 + joiner + s2
}
To call this method you would have to type something like let fullName = join("Harry", "Richardson", joiner: "-")
. You may not want to have to type joiner
in the method call though! You may be stuck in your ways and love the old non-Objective-C way of doing things. In which case, you would re-write that method signature as func join(s1: String, s2 : String, _ joiner : String = " ") -> String
- notice the underscore just before the third parameter. You can now call the method as let fullName = join("Harry", "Richardson", "-")
.
You will see external parameter names being used in Objective-C APIs all the time.