Swift Tutorials: Mutating Methods (in Structs)

beginner
18 min

Swift Tutorials: Mutating Methods (in Structs)

Welcome back to CodeYourCraft! Today, we're diving into an essential aspect of Swift programming - Mutating Methods, specifically within Structs. Let's get started! 🚀

What are Mutating Methods? 💡

Mutating methods are functions that can modify the properties of a struct. They are necessary because, by default, Swift's structs are immutable, meaning they cannot be changed once created.

Why use Mutating Methods in Structs? 📝

Mutating methods allow us to create modifiable structures, making them practical for real-world programming scenarios. They help maintain the safety and consistency of our code while providing the flexibility we need.

Creating a Struct 🎯

Before we dive into mutating methods, let's create a simple struct to work with:

swift
struct Person { var name: String var age: Int }

Defining a Mutating Method 💡

Now, let's make our Person struct modifiable by defining a mutating method:

swift
struct Person { var name: String var age: Int mutating func growOlder(by years: Int) { age += years } }

In the above example, we defined a mutating method called growOlder. This method increases the age property of the Person struct by the provided number of years.

Using Mutating Methods 🎯

Let's create an instance of our Person struct and use the mutating method:

swift
var john = Person(name: "John", age: 30) john.growOlder(by: 5) print(john) // Person(name: "John", age: 35)

In the example above, we created a Person instance named john. We then used the growOlder mutating method to make john older by 5 years.

Pro Tip 💡

Remember, you can't call a mutating method on a constant struct instance (i.e., let john = Person(name: "John", age: 30)). Always use a var to work with mutating methods.

Advanced Example 🎯

Let's create a struct for a Rectangle and define a mutating method to change its dimensions:

swift
struct Rectangle { var width: Double var height: Double mutating func changeSize(width: Double, height: Double) { self.width = width self.height = height } }

Now, let's create a Rectangle instance and change its size:

swift
var rect = Rectangle(width: 10.0, height: 5.0) rect.changeSize(width: 20.0, height: 10.0) print(rect) // Rectangle(width: 20.0, height: 10.0)

Quiz 🎯

Question: What does a mutating method do in Swift?

A: It creates a new instance of a struct B: It modifies the properties of a mutable struct C: It defines a new struct

Correct: B Explanation: Mutating methods modify the properties of a mutable struct in Swift.


And that's it for today! We've covered mutating methods and how to use them with structs in Swift. As always, keep practicing and stay curious! 🚀

Next time, we'll explore more advanced topics to help you become a proficient Swift developer. Until then, happy coding! 💻🤘