Pass a struct to a function in Swift

In this tutorial, we will learn how to pass a struct to a function (by using it as a parameter,)  in Swift. We will pass it just like we pass other data types.

We know that structs in Swift are passed by value, which means that a copy of the struct is passed to the function.

How to Pass a Struct to a Function in Swift

Let’s understand how we can do this through an easy example:

// I am defining a struct here
struct Person {
    var name: String
    var age: Int
}

// Creating a function that takes the struct as a parameter
func printPersonInfo(person: Person) {
    print("Name: \(person.name), Age: \(person.age)")
}

// Now creating an instance of that struct
let person1 = Person(name: "Clara", age: 30)

// Finally Passing the struct to the function
printPersonInfo(person: person1)

Output:

Name: Clara, Age: 30

In the above example, The Person struct is defined with two properties: name and age.

The function printPersonInfo is accepting a struct Person.

When person1 is passed to the function at the same time Swift is passing a copy of it, so any changes inside the function will not affect the original person1 value.

Leave a Reply

Your email address will not be published. Required fields are marked *