Function Parameters in Swift Tutorial

beginner
21 min

Function Parameters in Swift Tutorial

Welcome to our comprehensive guide on Function Parameters in Swift! This tutorial is designed to help both beginners and intermediate learners understand the concept from scratch. Let's dive in!

Understanding Function Parameters 🎯

In Swift, functions are blocks of code that perform specific tasks. Function parameters are the inputs provided to a function to perform these tasks.

Function Parameters Types 📝

Swift supports three types of function parameters:

  1. Value Parameters: These parameters pass the value by value, meaning the original value remains the same even after the function call.

  2. Reference (or Inout) Parameters: These parameters pass the reference of a variable, allowing the function to modify the original variable.

  3. Constant Parameters: These parameters are read-only within the function and must be initialized before being passed.

Value Parameters 🎯

Let's create a simple value parameter function that calculates the square of a number.

swift
func squareOf(number: Int) -> Int { return number * number }

In this example, number is a value parameter. The function takes an Int value, squares it, and returns the result.

Calling a Function with Value Parameters 💡

You can call the function using the following syntax:

swift
let result = squareOf(number: 5) print(result) // Output: 25

Reference (or Inout) Parameters 🎯

Reference parameters allow a function to modify the original variable. To create a reference parameter function, you need to use the inout keyword.

swift
func squareReference(number: inout Int) { number *= number }

Here, number is a reference parameter. The function takes an inout Int value, squares it, and modifies the original variable.

Calling a Function with Reference Parameters 💡

You can call the function using the following syntax:

swift
var number = 5 squareReference(number: &number) print(number) // Output: 25

Constants Parameters 🎯

A constant parameter must be initialized before it's passed to the function. Here's an example:

swift
func greet(name: String) { print("Hello, \(name)!") } let name = "John" greet(name: name) // Output: Hello, John!

In this example, name is a constant parameter. The function takes a String constant, greets the person, and prints the message.

Quiz Time 💡

Quick Quiz
Question 1 of 1

What is the difference between value parameters and reference parameters in Swift?

We hope this tutorial has helped you understand function parameters in Swift. Stay tuned for more advanced topics! 🚀💻