Swift: Parameters and Arguments

Parameters and Arguments in Swift:

Parameters have previously been defined as optional input values that exist between the () in a function definition. It accept the input function requires to complete a task directly.

A function’s parameters define as follows:

func functionName(nameofParameter: typeofParameter) -> returnType {
   // body of function 

In the above example, we define a parameter by separating its name and type with a :. This syntax should look familiar because it’s how we use type annotation to define a variable or constant.

Assume we want to calculate the area of square-shaped room. The following function can set up:

func roomArea(side: Float) -> Float {
  return side * side;

The function roomArea(side: Float) takes a single parameter of type Float, and returns a Float value. The result of multiplying side by side is returned within the function.

We’ll need to pass in a side argument when calling this function. When the function is called, an argument is the real value for a parameter.

let calculatedArea = roomArea(side: 12.5); 
print(calculatedArea); // Prints: 156.25

The argument, 12.5 for the side parameter in the function call, is passed in. The compiler will know to replace side in the function body with 12.5 and return the result of 12.5 * 12.5. The calculatedArea variable is then set to this product, which is then printed to the console.

There are a few rules to remember when it comes to parameters and arguments:

  • When a function is called, an argument must be passed in if a parameter exists. Otherwise, an error will be thrown by the compiler.
  • The parameter’s argument must be of the same type as the parameter’s declared value.
  • Include the parameter name(s) in the function’s title, followed by a colon.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: