Leave a rating/review
Notes: 37. Challenge: Functions
Update Notes: The student materials have been reviewed and are updated as of October 2021.
It’s time for your next challenge! You can find the challenge in the “04 - Challenge - Functions” page of the playground you’ve been using, or you can download a new one from the resources for this video. Open it up, and try solving the challenge questions on your own, then keep watching to compare your work to mine. Good luck!
First: Write a function named printFullName that takes two strings called firstName and lastName. I’ll start with they func keyword, name the function printFullName, and add two String parameters inside the parenthesis.
func printFullName(firstName: String, lastName: String) {
}
Then in the body of the function, I’ll print out those two parameters with a space in between.
print(firstName + " " + lastName)
And now I can use function to print out my own name:
printFullName(firstName: "Chris", lastName: "Belanger")
- There I am! Chris Belanger.
To finish up challenge one, I need to remove the argument labels from the function call. All that requires is an underscore before each parameter name to say that I don’t want any argument labels for this function.
func printFullName(_ firstName: String, _ lastName: String) {
Then the function call needs to be changed to match.
printFullName("Chris", "Belanger")
The next challenge is similar to the first. I still need to assemble a full name from a first and last name, so I’ll copy and paste the function. This version should return the full name, so I’ll rename the function calculateFullName.
func calculateFullName(_ firstName: String, _ lastName: String) {
print(firstName + " " + lastName)
}
To make this return value, I need to add the return type, String, to the function declaration.
func calculateFullName(...) -> String {
And then I need to add a return statement to the body to return this string, instead of printing it.
return firstName + " " + lastName
The last thing to do is store my name in a new constant. And check my full name in the sidebar!
let fullName = calculateFullName("Chris", "Belanger")