Imagine that we are building a contacts app to hold the details of your family and friends, and we want to create a string of a contact's full name. Let's explore some of the ways functions can be used:
// Input parameters and output
func fullName(givenName: String, middleName: String, familyName: String) -> String {
return "\(givenName) \(middleName) \(familyName)"
}
The preceding function takes three string parameters and outputs a string that puts all these together with spaces in between and returns the resulting string. The only thing this function does is take some inputs and produce an output without causing any side effects; this type of function is often called a pure function. To call this function, we enter the name of the function followed by the input parameters within () brackets, where each parameter value is preceded by its label:
let myFullName = fullName(givenName: "Keith", middleName: "David", familyName: "Moon")
print(myFullName) // Keith David Moon
Since the function returns a value, we can assign the output of this function to a constant or a variable, just like any other expression:
// Input parameters, with a side effect and no output
func printFullName(givenName: String, middleName: String, familyName: String) {
print("\(givenName) \(middleName) \(familyName)")
}
The next function takes the same input parameters, but its goal is not to return a value. Instead, it prints out the parameters as one string separated by spaces:
printFullName(givenName: "Keith", middleName: "David", familyName: "Moon")
We can call this function in the same way as the preceding function, although it can't be assigned to anything since it doesn't have a return value:
// No inputs, with an output
func authorsFullName() -> String {
return fullName(givenName: "Keith", middleName: "David", familyName: "Moon")
}
The preceding function takes no parameters as everything it needs to perform its task is contained within it, although it does output a string. This function calls the fullName function we defined earlier, taking advantage of its ability to produce a full name when given the component names; reusing is the most useful feature that functions provide:
let authorOfThisBook = authorsFullName()
Since authorsFullName takes no parameters, we can execute it by entering the function name followed by empty brackets (), and since it returns a value, we can assign the outcome of authorsFullName to a variable:
// No inputs, no ouput
func printAuthorsFullName() {
let author = authorsFullName()
print(author)
}
Our final example takes no parameters and returns no value:
printAuthorsFullName()
You can call this function in the same way as the previous functions with no parameters, but there is no return value to assign.
As you can see from the preceding examples, having input parameters and providing an output value are not required when defining a function.