Swift functions
up:: Swift ⚐
Named parameters and labels
Swift requires specifying parameter names
JavaScript Functions generally1 don’t use named parameters:
function sayHello(name: string, day: string) {
return `Hello ${name}, the day is ${day}`
}
// called with
sayHello("John", "Tuesday")
But in Swift, we have to specify the parameter name:
func sayHello(name: String, day: String) -> String {
return "Hello \(name), the day is \(day)"
}
// called with
sayHello(name: "John", day: "Tuesday")
Using labels for parameter names
By prepending a string before the parameter name, we add a label.
func sayHello(to name: String, onDay day: String) -> String {
return "Hello \(name), the day is \(day)"
}
// called with
sayHello(to: "John", onDay: "Tuesday")
Ideally, function names and parameter labels combine to make function calls similar to sentences.
Argument labels can be blank
func say(_ message: String) {
print("I say: '\(message)'")
}
say("Hello")
This way Swift functions behave more like JavaScript functions.
Links
Footnotes
-
Although you can simulate it with parameter destructuring, or other hackery. ↩