Start learning free

LESSON 40 OF 415 · FUNCTIONS I

Create a Function with Parameters in Swift

Practice Read the full explanation

We've written this code:

func mainFunction() {
	print("My name is Andy")
	print("I code in Python")
	print("I have a dog")

	print("My name is Mike")
	print("I code in Java")
	print("I have a cat")

	print("My name is Sarah")
	print("I code in JavaScript")
	print("I have a parrot")
}

Write the same code in a better way by creating and calling a function with parameters printMessages()

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · FUNCTIONS I

    Exercise Create Function With Parameters in Swift, explained

    Problem overview

    The starting code prints three short introductions by repeating nine print calls inside mainFunction. Each introduction has the same three sentences, and only three words change: the person's name, the programming language and the pet.

    func mainFunction() {
        print("My name is Andy")
        print("I code in Python")
        print("I have a dog")
        // ... the same three lines again for Mike and Sarah
    }
    

    The task is to write the same program in a better way: a function printMessages that takes the three changing words as parameters, called once per person. The output must stay exactly the same, nine lines in all.

    Approach

    When the same lines appear several times with only some values changed, turn those values into parameters. The function holds the shared lines once, and each call supplies its own values. The program gets shorter, and a change such as a new sentence is made in one place.

    Step by step

    1. Define the function above mainFunction. It needs three parameters: name, language and animal, each a String. The lesson puts an underscore before each name, so callers pass plain values without labels.
    2. Print the three sentences. Each sentence is a fixed start plus one parameter. String interpolation puts the parameter inside the literal: "My name is \(name)".
    3. Call the function three times from mainFunction. The arguments must be in the order of the parameters: name, language, animal. Use "Andy", "Python", "dog", then "Mike", "Java", "cat", then "Sarah", "JavaScript", "parrot".

    The solution in Swift

    // Define and implement the function printMessages here:
    func printMessages(_ name: String, _ language: String, _ animal: String) {
        print("My name is \(name)")
        print("I code in \(language)")
        print("I have a \(animal)")
    }
    
    
    func mainFunction() {
        // Call printMessages 3 times here:
        printMessages("Andy", "Python", "dog")
        printMessages("Mike", "Java", "cat")
        printMessages("Sarah", "JavaScript", "parrot")
    }
    

    Running mainFunction() prints:

    My name is Andy
    I code in Python
    I have a dog
    My name is Mike
    I code in Java
    I have a cat
    My name is Sarah
    I code in JavaScript
    I have a parrot
    

    Some Swift details about this code:

    • The underscore removes a label. Without it, the parameters would be labelled and a call would read printMessages(name: "Andy", language: "Python", animal: "dog"). With the underscores, the call shown above is the only valid form.
    • Types are required. Swift needs a type on every parameter. Passing a number where a String is expected is a compile error.
    • Interpolation takes any value. \(name) works for a String and for numbers as well. Joining with + would work here too, but interpolation avoids missing spaces.

    Common mistakes

    • Wrong argument order. printMessages("Python", "Andy", "dog") compiles, since all three are strings, and prints My name is Python.
    • Wrong number of arguments. Passing two arguments fails with "missing argument for parameter #3 in call".
    • Putting the parameter inside the quotes. print("My name is name") prints the word name, not its value.
    • Defining but not calling. If mainFunction doesn't call printMessages, nothing is printed.
    • A different spacing or wording. The sentences must match the original exactly, including the capital letters and the space before the value.

    Testing

    A new call shows how much the function now saves. Adding one more person takes a single line:

    printMessages("Ana", "Swift", "turtle")
    

    This prints My name is Ana, I code in Swift and I have a turtle. In the original version the same change needed three new print lines, and any change to the wording meant editing every block.

    Key takeaways

    • Repeated code with a few changing values is a sign you need a function with parameters.
    • Arguments are matched to parameters by position.
    • Interpolation with \(...) is the neat way to put a parameter into a string.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free