0
0
Swiftprogramming~5 mins

Methods in structs in Swift

Choose your learning style9 modes available
Introduction

Methods inside structs let you add actions that the struct can do. This helps keep data and behavior together, like a mini toolbox.

When you want to group related data and actions, like a shape that can calculate its area.
When you want to change or use the data inside a struct in a neat way.
When you want to keep your code organized by putting functions inside the struct they belong to.
When you want to create reusable pieces of code that represent real-world things with both data and actions.
Syntax
Swift
struct StructName {
    // properties
    func methodName() {
        // code to do something
    }
    mutating func changeMethod() {
        // code that changes properties
    }
}

Use func to define a method inside a struct.

If the method changes properties, mark it with mutating.

Examples
This struct has a method area() that calculates the circle's area.
Swift
struct Circle {
    var radius: Double
    func area() -> Double {
        return 3.14 * radius * radius
    }
}
This struct has a method increment() that changes the count property, so it uses mutating.
Swift
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}
Sample Program

This program creates a rectangle, prints its area, doubles its size using a mutating method, then prints the new area.

Swift
struct Rectangle {
    var width: Double
    var height: Double

    func area() -> Double {
        return width * height
    }

    mutating func doubleSize() {
        width *= 2
        height *= 2
    }
}

var rect = Rectangle(width: 3, height: 4)
print("Area before doubling: \(rect.area())")
rect.doubleSize()
print("Area after doubling: \(rect.area())")
OutputSuccess
Important Notes

Remember to use mutating only when the method changes the struct's properties.

Methods help keep your code clean and related data and actions together.

Summary

Methods are functions inside structs that let structs do things.

Use mutating for methods that change properties.

Methods help organize code by combining data and behavior.