The function in the example below is called greet(person:)
, because that’s what it does—it takes a person’s name as input and returns a greeting for that person. To accomplish this, you define one input parameter—a String
value called person
—and a return type of String
, which will contain a greeting for that person:
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
All of this information is rolled up into the function’s definition, which is prefixed with the func
keyword. You indicate the function’s return type with the return arrow ->
(a hyphen followed by a right angle bracket), which is followed by the name of the type to return.
The definition describes what the function does, what it expects to receive, and what it returns when it is done. The definition makes it easy for the function to be called unambiguously from elsewhere in your code:
print(greet(person: "Anna"))
// Prints "Hello, Anna!"
print(greet(person: "Brian"))
// Prints "Hello, Brian!"