Learn
Functions
Parameters and Arguments

We’ve referenced the term, parameters, previously as optional input values that exist between the () in a function definition. In the previous exercise, the findAge() function operated on the values of a global variable and constant. Each time we’d need to calculate a different outcome, we’d have to edit their values.

Parameters can lessen this burden by allowing a function to directly accept the input it needs to execute a task.

Parameters are defined in a function as follows:

func someFunction(paramName: paramType) -> returnType {
   // function body where paramName can be used
}

In the example above, we define a parameter with its name and type, separated by a :. This syntax should look familiar since it’s how we can define a variable or constant using type annotation.

Assume we have a garden in the shape of a square whose area we need to calculate. We can set up the following function:

func findGardenArea(side: Int) -> Int { return side * side }

The function above, findGardenArea(side:), accepts a single parameter, side, of the type, Int, and returns a value of the Int type. Within the function, the result of multiplying side by side is returned.

When calling this function, we will need to pass in an argument for side. An argument is the real value for a parameter when the function is called.

var area = findGardenArea(side: 5) print(area) // Prints: 25

On the first line above, we pass in the argument, 5 for the side parameter in the function call. With this, the compiler knows to replace side with 5 in the function body and return the result of 5 * 5. This product is then stored in the variable area and printed to the terminal.

Some rules to keep in mind about parameters and arguments:

  • If a parameter exists, an argument must be passed in when the function is called. Otherwise, the compiler will throw an error.
  • The argument must be the same type of value that the parameter is declared to have.
  • When referencing a function, include the parameter name(s) in its title followed by a colon such as findGardenArea(side:).

Instructions

1.

Assume we’re writing a program that contains formulas we’ll need for the Geometry Regent. One of these formulas is the Circumference of a Circle.

  • In Circumference.swift, define a function, findCircumference(), that will accept a diameter parameter of type Double, and return a Double type.

  • Within findCircumference(), use the return keyword to return the expression, 3.14 * diameter.

2.

Call the function and pass in a number argument for the diameter parameter. Save this function call in the variable, result.

On the following line, print the value of result.

Folder Icon

Take this course for free

Already have an account?