0
0
Swiftprogramming~5 mins

Adding methods in Swift

Choose your learning style9 modes available
Introduction

Methods let you add actions or behaviors to your types, like functions that belong to a specific thing.

When you want to describe what an object can do, like a car that can start or stop.
When you want to organize code related to a specific type, keeping it neat and easy to understand.
When you want to reuse code that works on the data inside your type.
When you want to change or update the data inside your type safely.
Syntax
Swift
struct TypeName {
    func methodName() {
        // code to perform action
    }
}

Methods are written inside a type like a struct or class.

Use func keyword to define a method.

Examples
This method bark() makes the dog say "Woof!" when called.
Swift
struct Dog {
    func bark() {
        print("Woof!")
    }
}
This method increment() changes the count value by adding 1. It uses mutating because it changes the struct's data.
Swift
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}
Sample Program

This program creates a Light with a method to switch it on or off. It shows the state before and after toggling.

Swift
struct Light {
    var isOn = false
    mutating func toggle() {
        isOn = !isOn
    }
}

var lamp = Light()
print("Lamp is on? \(lamp.isOn)")
lamp.toggle()
print("Lamp is on? \(lamp.isOn)")
OutputSuccess
Important Notes

Use mutating keyword in methods that change properties of structs or enums.

Classes do not need mutating because they are reference types.

Summary

Methods add actions to your types, like functions inside a struct or class.

Use func to define a method, and mutating if it changes struct data.

Methods help organize and reuse code related to specific data.